<?php
/**
 * 春哥团队（www.cgtblog.com） - 春哥多端多商户万能DIY商城系统
 * Copyright © 2024 春哥技术团队 保留所有权利
 * =========================================================

 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\common;
use think\facade\Db;
use think\facade\Log;


class Member
{
    //升级
	public static function uplv($aid,$mid,$type='shop'){
		$member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
        if(!$member['id']) return;
		if(getcustom('member_level_down_commission')){
			if($member['isauto_down']==1){
				return;
			}
		}
		self::douplv($aid,$member,$type);
		//他的上级
		if($member['path']){
			$parentList = Db::name('member')->where('aid',$aid)->where('id','in',$member['path'])->order(Db::raw('field(id,'.$member['path'].')'))->select()->toArray();
			if($parentList){
				$parentList = array_reverse($parentList);
				foreach($parentList as $parent){
					self::douplv($aid,$parent,$type);
				}
			}
		}
	}
    public static function douplv($aid,$member,$type='shop'){
		$mid = $member['id'];
        $wxpaymoney = 0 + Db::name('wxpay_log')->where('aid',$aid)->where('mid',$mid)->sum('total_fee');
        if($type=='cashier'){
            $ordermoney = 0 + Db::name('cashier_order')->where('aid',$aid)->where('mid',$mid)->where('status',1)->sum('totalprice');
        }else{
            $ordermoney = 0 + Db::name('shop_order')->where('aid',$aid)->where('mid',$mid)->where('status','in','1,2,3')->sum('totalprice');
        }
        
        $rechargemoney = 0 + Db::name('recharge_order')->where('aid',$aid)->where('mid',$mid)->where('status',1)->sum('money');
		if(getcustom('member_level_down_commission')){
			if($member['isauto_down']==1){
				return;
			}
		}
        self::upLevel($aid, $member, $member, $ordermoney, $wxpaymoney, $rechargemoney);

        //其他分组等级
        if(getcustom('plug_sanyang')) {
            $categoryList = Db::name('member_level_category')->where('aid',$aid)->where('isdefault', 0)->where('status', 1)->select()->toArray();
            if($categoryList) {
                foreach ($categoryList as $cat) {
                    $level_records = Db::name('member_level_record')->where('aid',$aid)->where('mid',$mid)->where('cid', $cat['id'])->find();
                    $level_records = $level_records ? $level_records : [];//无其他分组等级
                    self::upLevel($aid, $member, $level_records, $ordermoney, $wxpaymoney, $rechargemoney, $cat['id']);
                }
            }
        }
    }

    /**
     * @param $aid
     * @param $member
     * @param $levelInfo 等级信息 levelid,levelstarttime
     * @param $ordermoney
     * @param $wxpaymoney
     * @param $rechargemoney
     * @param $cid 其他分组等级为空时使用此字段
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function upLevel($aid, $member, $levelInfo, $ordermoney, $wxpaymoney, $rechargemoney, $cid = 0)
    {
        $mid = $member['id'];
        $nowlv = ['sort' => -1];
        if($levelInfo['levelid'])
            $nowlv = Db::name('member_level')->where('aid',$aid)->where('id',$levelInfo['levelid'])->find();
        $cid = $cid ? $cid : $nowlv['cid'];
        //等级列表
        $lvlist = Db::name('member_level')->where('aid',$aid)->where('cid', $cid)->where('can_up',1)->where('sort','>',$nowlv['sort'])->order('sort,id')->select();
        $newlv = $nowlv;
        foreach($lvlist as $lv){
            $isup = false;
            if(getcustom('levelup_from_levelid')) {
                //升级前置等级条件
                $gettj = explode(',',$lv['gettj']);
                if ($lv['gettj'] && !in_array('-1', $gettj) && !in_array($nowlv['id'], $gettj)) {
                    continue;
                }
            }
            $condition_or = false;
			if($lv['maxnum'] > 0){
				$lvmembercount = Db::name('member')->where('aid',$aid)->where('levelid',$lv['id'])->count();
				if($lvmembercount >= $lv['maxnum']) continue;
			}
            if(($lv['up_ordermoney']>0 && $lv['up_ordermoney'] <= $ordermoney) || ($lv['up_wxpaymoney']>0 && $lv['up_wxpaymoney'] <= $wxpaymoney)|| ($lv['up_rechargemoney']>0 && $lv['up_rechargemoney'] <= $rechargemoney) || ($member['card_code'] && $lv['up_getmembercard']==1)){
                $isup = true;
            }
            if(!$isup && $lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'or'){
				if($lv['up_fxordermoney_removemax'] ==1){
					$downmids = self::getdownmids_removemax($aid,$mid,$lv['up_fxorderlevelnum'],$lv['up_fxorderlevelid']);
					//\think\facade\Log::write('---'.$mid.'去除最高的业绩后会员id---');
					//\think\facade\Log::write($downmids);
				}else{
					$downmids = self::getdownmids($aid,$mid,$lv['up_fxorderlevelnum'],$lv['up_fxorderlevelid']);
				}
                if($downmids){
                    $fxordermoney = 0 + Db::name('shop_order_goods')->where('status','in','1,2,3')->where('mid','in',$downmids)->sum('totalprice');
                    if($fxordermoney >= $lv['up_fxordermoney']){
                        $isup = true;
                    }
                }
            }
            if(!$isup && $lv['up_fxordermoney_xiao'] > 0){
                $downmids = self::getdownmids_xiao($aid,$mid,$lv['up_fxorderlevelnum_xiao'],$lv['up_fxorderlevelid_xiao']);
                if($downmids){
                    $fxordermoney = 0 + Db::name('shop_order_goods')->where('status','in','1,2,3')->where('mid','in',$downmids)->sum('totalprice');
                    if($fxordermoney >= $lv['up_fxordermoney_xiao']){
                        $isup = true;
                    }
                }
            }
            if(!$isup && ($lv['up_fxdowncount']>0 || $lv['up_fxdowncount2']>0 || $lv['up_fxdowncount3']>0)){
                $downmidcount1 = 0;
                $downmidcount2 = 0;
                $downmidcount3 = 0;
                $up_fxdowncount = intval($lv['up_fxdowncount']);
                $up_fxdowncount2 = intval($lv['up_fxdowncount2']);
                $up_fxdowncount3 = intval($lv['up_fxdowncount3']);
                if($lv['up_fxdowncount'] > 0){
                    $downmids = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum'],$lv['up_fxdownlevelid'],$lv['up_with_origin'],$lv['up_with_new']);
                    $downmidcount1 = count($downmids);
                }
                if($lv['up_fxdowncount2'] > 0){
                    $downmids2 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum2'],$lv['up_fxdownlevelid2'],$lv['up_with_origin'],$lv['up_with_new']);
                    $downmidcount2 = count($downmids2);
                }
                if($lv['up_fxdowncount3'] > 0){
                    $downmids3 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum3'],$lv['up_fxdownlevelid3'],$lv['up_with_origin'],$lv['up_with_new']);
                    $downmidcount3 = count($downmids3);
                }
                if($downmidcount1 >= $up_fxdowncount && $downmidcount2 >= $up_fxdowncount2 && $downmidcount3 >= $up_fxdowncount3){
                    $isup = true;
                }
            }
			if(getcustom('up_downbuyprocount') && !$isup && $lv['up_downbuypronum']>0){
				$downmids = self::getdownmids($aid,$mid,$lv['up_downbuyprolvnum']);
                $downbuypronum = 0;
                if($downmids){
                    if($lv['up_downbuyproid']){
                        $downbuypronum = Db::name('shop_order_goods')->where('aid',$aid)->where('status','in','1,2,3')->where('mid','in',$downmids)->where('proid','in',$lv['up_downbuyproid'])->sum('num');
                    }else{
                        $downbuypronum = Db::name('shop_order_goods')->where('aid',$aid)->where('status','in','1,2,3')->where('mid','in',$downmids)->sum('num');
                    }
                    if($downbuypronum >= $lv['up_downbuypronum']){
                        $isup = true;
                    }
                }
			}
            if(getcustom('up_cat_ordermoney')){
                if(!$isup && ($lv['up_cat_ordermoney']>0 && $lv['up_catid']!='')){
                    //购买分类商品,单笔订单金额满
                    //查询最后一笔订单
                    $up_catids = explode(',',str_replace('，',',',$lv['up_catid']));
                    $last_order = Db::name('shop_order')->field('id,aid,bid,mid,ordernum,totalprice,status')->where('aid',$aid)->where('mid',$mid)->where('status','in','1,2,3')->order('id desc')->find();
                    if($last_order['totalprice'] >= $lv['up_cat_ordermoney']){
                        $oglist = Db::name('shop_order_goods')->field('id,aid,bid,mid,orderid,proid,cid,real_totalprice,status')->where('aid',$aid)->where('mid',$mid)->where('status','in','1,2,3')->where('orderid',$last_order['id'])->select()->toArray();
                        if($oglist){
                            $allcids=[];
                            $up_cat_total=0;
                            $cids = Db::name('shop_category')->where('id','in',$lv['up_catid'])->where('aid',$aid)->column('id');
                            if($cids){
                                $cids2 = Db::name('shop_category')->where('aid',$aid)->where('pid','in',$cids)->column('id');
                                if($cids2){
                                    $cids3 = Db::name('shop_category')->where('aid',$aid)->where('pid','in',$cids2)->column('id');
                                    if($cids3)
                                        $allcids = array_merge($cids,$cids2,$cids3);
                                    else
                                        $allcids = array_merge($cids,$cids2);
                                }else{
                                    $allcids = $cids;
                                }
                                foreach ($oglist as $og){
                                    $ogcid = explode(',',$og['cid']);
                                    if(empty($ogcid)) continue;
                                    if(array_intersect($allcids,$ogcid)){
                                        $up_cat_total += $og['real_totalprice'];
                                    }
                                }
                                if($up_cat_total >= $lv['up_cat_ordermoney']){
                                    $isup = true;
                                }
                            }
                        }
                    }
                }
            }
            //购买指定商品 的条件
            if($lv['up_buygoods_condition'] == 'and' && ($lv['up_proid']!='0' && $lv['up_proid']!='')) {
                $isup = false;
            }
            if(!$isup && ($lv['up_proid']!='0' && $lv['up_proid']!='')){ //购买指定商品
                $up_proids = explode(',',str_replace('，',',',$lv['up_proid']));
                $up_pronums = explode(',',str_replace('，',',',$lv['up_pronum']));
                if(count($up_pronums) > 1) {
                    foreach($up_proids as $k=>$up_proid){
                        $pronum = $up_pronums[$k];
                        if(!$pronum) $pronum = 1;
                        $buynum = Db::name('shop_order_goods')->where('aid',$aid)->where('mid',$mid)->where('proid',$up_proid)->where('status','in','1,2,3')->sum('num');
                        if($buynum >= $pronum){
                            $isup = true;
//                        break;
                        }
                    }
                } else {
                    $pronum = $up_pronums[0];
                    if(!$pronum) $pronum = 1;
                    $buynum = 0;
                    foreach($up_proids as $k=>$up_proid){
                        $buynum += Db::name('shop_order_goods')->where('aid',$aid)->where('mid',$mid)->where('proid',$up_proid)->where('status','in','1,2,3')->sum('num');
                        if($buynum >= $pronum){
                            $isup = true;
//                        break;
                        }
                    }
                }
            }
            if(getcustom('member_levelup_businessnum')){
                if(!$isup && $lv['up_businessnum']>0){
                    //查询他推荐的商户数量
                    $businessnum = 0+Db::name('business')
                        ->alias('b')
                        ->join('member m','m.id = b.mid')
                        ->where('b.aid',$aid)
                        ->where('b.status',1)
                        ->where('m.pid',$mid)
                        ->count();
                    if($businessnum >= $lv['up_businessnum']){
                        $isup = true;
                    }
                }
            }
            //是否包含or的条件
            if($lv['up_ordermoney']>0 || $lv['up_wxpaymoney']>0 || $lv['up_rechargemoney']>0 || $lv['up_getmembercard']==1 || ($lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'or') || $lv['up_fxordermoney_xiao'] > 0
             || $lv['up_fxdowncount']>0 || $lv['up_fxdowncount2']>0 || $lv['up_fxdowncount3']>0 || ($lv['up_proid']!='0' && $lv['up_proid']!=''  && $lv['up_buygoods_condition'] == 'or')) {
                $condition_or = true;
            }

            if(($isup || ($isup === false && $condition_or === false)) && $lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'and'){
				if($lv['up_fxordermoney_removemax'] ==1){
					$downmids = self::getdownmids_removemax($aid,$mid,$lv['up_fxorderlevelnum'],$lv['up_fxorderlevelid']);
				}else{
					$downmids = self::getdownmids($aid,$mid,$lv['up_fxorderlevelnum'],$lv['up_fxorderlevelid']);
				}
                if($downmids){
                    $fxordermoney = 0 + Db::name('shop_order_goods')->where('status','in','1,2,3')->where('mid','in',$downmids)->sum('totalprice');
                    if($fxordermoney >= $lv['up_fxordermoney']){
                        $isup_up_fxordermoney = true;
                    } else {
                        $isup = false;
                    }
                }else{
                    $isup = false;
                }
            }
			if(getcustom('up_fxdowncount_and_isor')){
				$isup_up_fxdowncount_and = true;
				if(!$isup && ($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)){
					$downmidcount1 = 0;
					$downmidcount2 = 0;
					$up_fxdowncount = intval($lv['up_fxdowncount_and']);
					$up_fxdowncount2 = intval($lv['up_fxdowncount2_and']);
					if($lv['up_fxdowncount_and'] > 0){
						$downmids = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum_and'],$lv['up_fxdownlevelid_and'],$lv['up_with_origin'],$lv['up_with_new']);
						$downmidcount1 = count($downmids);
					}
					if($lv['up_fxdowncount2_and'] > 0){
						$downmids2 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum2_and'],$lv['up_fxdownlevelid2_and'],$lv['up_with_origin'],$lv['up_with_new']);
						$downmidcount2 = count($downmids2);
					}
					if($downmidcount1 >= $up_fxdowncount && $downmidcount2 >= $up_fxdowncount2){
						$isup = true;
					}
				}
			}else{
                $isup_up_fxdowncount_and = false;
				//没设置或条件$isup === false && $condition_or === false
				if(($isup || ($isup === false && $condition_or === false)) && ($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)){
					$downmidcount1 = 0;
					$downmidcount2 = 0;
					$up_fxdowncount = intval($lv['up_fxdowncount_and']);
					$up_fxdowncount2 = intval($lv['up_fxdowncount2_and']);
					if($lv['up_fxdowncount_and'] > 0){
						$downmids = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum_and'],$lv['up_fxdownlevelid_and'],$lv['up_with_origin'],$lv['up_with_new']);
						$downmidcount1 = count($downmids);
					}
					if($lv['up_fxdowncount2_and'] > 0){
						$downmids2 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum2_and'],$lv['up_fxdownlevelid2_and'],$lv['up_with_origin'],$lv['up_with_new']);
						$downmidcount2 = count($downmids2);
					}
					if($downmidcount1 >= $up_fxdowncount && $downmidcount2 >= $up_fxdowncount2){
						$isup_up_fxdowncount_and = true;
					} else {
						$isup = false;
					}
				}
			}
            if($isup || ($isup === false && $condition_or === false)) {
                if(($lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'and') && ($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)) {
                    if($isup_up_fxordermoney && $isup_up_fxdowncount_and) {
                        $isup = true;
                    }
                }elseif(!($lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'and') && ($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)) {
                    if($isup_up_fxdowncount_and) {
                        $isup = true;
                    }
                }elseif(($lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'and') && !($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)) {
                    if($isup_up_fxordermoney) {
                        $isup = true;
                    }
                }
            }
            if(getcustom('up_fxorder_condition_new')){
                /********************************新增升级条件start 20231104*******************************************/
                //四组下级人数任意搭配
                if($lv['up_fxdowncount_new']>0 || $lv['up_fxdowncount2_new']>0 || $lv['up_fxdowncount3_new']>0 || $lv['up_fxdowncount4_new']>0){
                    $downmidcount1 = 0;
                    $downmidcount2 = 0;
                    $downmidcount3 = 0;
                    $downmidcount4 = 0;
                    $up_fxdowncount = intval($lv['up_fxdowncount_new']);
                    $up_fxdowncount2 = intval($lv['up_fxdowncount2_new']);
                    $up_fxdowncount3 = intval($lv['up_fxdowncount3_new']);
                    $up_fxdowncount4 = intval($lv['up_fxdowncount4_new']);
                    if($lv['up_fxdowncount_new'] > 0){
                        $downmids = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum_new'],$lv['up_fxdownlevelid_new'],$lv['up_with_origin'],$lv['up_with_new']);
                        $downmidcount1 = count($downmids);
                    }
                    if($lv['up_fxdowncount2_new'] > 0){
                        $downmids2 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum2_new'],$lv['up_fxdownlevelid2_new'],$lv['up_with_origin'],$lv['up_with_new']);
                        $downmidcount2 = count($downmids2);
                    }
                    if($lv['up_fxdowncount3_new'] > 0){
                        $downmids3 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum3_new'],$lv['up_fxdownlevelid3_new'],$lv['up_with_origin'],$lv['up_with_new']);
                        $downmidcount3 = count($downmids3);
                    }
                    if($lv['up_fxdowncount4_new'] > 0){
                        $downmids4 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum4_new'],$lv['up_fxdownlevelid4_new'],$lv['up_with_origin'],$lv['up_with_new']);
                        $downmidcount4 = count($downmids4);
                    }
                    $logic_str = $lv['up_fxorder_condition_new']=='and'?'&&':'||';
                    $logic_str2 = $lv['up_fxorder_condition2_new']=='and'?'&&':'||';
                    $logic_str3 = $lv['up_fxorder_condition3_new']=='and'?'&&':'||';
                    $logic_str4 = $lv['up_fxorder_condition4_new']=='and'?'&&':'||';
                    //dump('前面所有条件的判断',$isup);
                    //依次根据上一个条件的逻辑判断结果进行下一个条件的判断
                    $isup_int = $isup==true?1:0;
                    if($up_fxdowncount>0){
                        $isup = eval("return ".$isup_int." ".$logic_str." ".$downmidcount1.">=".$up_fxdowncount.";");
                        //dump($isup_int." ".$logic_str." ".$downmidcount1.">=".$up_fxdowncount);
                        //dump('逻辑1判断',$isup);
                        $isup_int = $isup==true?1:0;
                    }
                    if($up_fxdowncount2>0){
                        $isup = eval("return ".$isup_int." ".$logic_str2." ".$downmidcount2.">=".$up_fxdowncount2.";");
                        //dump('逻辑2判断',$isup);
                        $isup_int = $isup==true?1:0;
                    }
                    if($up_fxdowncount3>0){
                        $isup = eval("return ".$isup_int." ".$logic_str3." ".$downmidcount3.">=".$up_fxdowncount3.";");
                        //dump('逻辑3判断',$isup);
                        $isup_int = $isup==true?1:0;
                    }
                    if($up_fxdowncount4>0){
                        $isup = eval("return ".$isup_int." ".$logic_str4." ".$downmidcount4.">=".$up_fxdowncount4.";");
                        //dump('逻辑4判断',$isup);
                    }

                }
                /********************************新增升级条件end 20231104*******************************************/
            }
            if(getcustom('up_level_teamorder')){
                //*****************************根据团队订单升级start 20231106*********************************************
                if($lv['up_teamorder_num']>0 || $lv['up_teamorder_small_num']>0){
                    $logic_str = $lv['up_teamorder_condition']=='and'?'&&':'||';
                    $logic_str2 = $lv['up_teamorder_small_condition']=='and'?'&&':'||';
                    //查询团队订单数量
                    $order_count = self::getTeamOrderNum($aid,$mid,$lv['up_teamorder_lv'],$lv['up_teamorder_levelid']);
                    $teamorder_count = $order_count['teamorder_count']??0;
                    //查询小区团队订单数量
                    $teamorder_small_count = $order_count['teamorder_small_count']??0;
                    //dump('团队订单数量'.$teamorder_count.'小区团队订单数量'.$teamorder_small_count);
                    //判断团队订单逻辑是否符合
                    $isup_int = $isup==true?1:0;
                    //dump('前面所有条件的判断'.$isup_int);
                    $isup = eval("return ".$isup_int." ".$logic_str." ".$teamorder_count.">=".$lv['up_teamorder_num'].";");
                    //dump('团队订单判断'.$isup_int);
                    //判断团队小区订单逻辑是否符合
                    $isup_int = $isup==true?1:0;
                    $isup = eval("return ".$isup_int." ".$logic_str2." ".$teamorder_small_count.">=".$lv['up_teamorder_small_num'].";");
                    //dump('小区团队订单判断'.$isup_int);
                }
                //*****************************根据团队订单升级end 20231106*********************************************
            }

            if($isup) $newlv = $lv;
        }
        //开启升级协议先记录，等前台点击同意协议再进行升级
        if(getcustom('up_level_agree') && !empty($newlv['is_agree'])){
            if($newlv && $newlv['id'] != $levelInfo['levelid']) {
                $update = [];
                $update['aid'] = $aid;
                $update['mid'] = $mid;
                $update['newlv_id'] = $newlv['id'];
                $update['sort'] = $newlv['sort'];
                $update['cid'] = $cid;
                $update['w_time'] = time();
                Db::name('member_level_agree')->insert($update);
            }
        }else{
			self::handleUpLevel($aid,$mid,$newlv,$levelInfo,$member,$cid);
        }

        if(!$isup && $newlv['id'] == $nowlv['id']){
            if(getcustom('levelup_pro_extend_time') && $nowlv['up_pro_extend_time'] == 1 && $nowlv['up_pro_keep_time'] == 0){
                //不升级，判断是否延期，通过member_levelup_order的时间对比订单时间
                //注意两种方式不可同时开启
                if($nowlv['yxqdate'] > 0){
                    $isextend = false;
                    $last_levelup_order = Db::name('member_levelup_order')->where('aid',$aid)->where('mid',$mid)->where('levelid',$nowlv['id'])->order('createtime','desc')->find();
                    $have_orderids = Db::name('shop_order')->where('aid',$aid)->where('mid',$mid)->where('createtime','>',$last_levelup_order['createtime'])->whereIn('status',[1,2,3])->column('id');
                    if($have_orderids){
                        $up_proids = explode(',',str_replace('，',',',$nowlv['up_proid']));
                        $up_pronums = explode(',',str_replace('，',',',$nowlv['up_pronum']));
                        if(count($up_pronums) > 1) {
                            foreach($up_proids as $k=>$up_proid){
                                $pronum = $up_pronums[$k];
                                if(!$pronum) $pronum = 1;
                                $buynum = Db::name('shop_order_goods')->where('aid',$aid)->where('mid',$mid)->where('proid',$up_proid)->whereIn('orderid',$have_orderids)->where('status','in','1,2,3')->sum('num');
                                if($buynum >= $pronum){
                                    $isextend = true;
                                }
                            }
                        } else {
                            $pronum = $up_pronums[0];
                            if(!$pronum) $pronum = 1;
                            $buynum = 0;
                            foreach($up_proids as $k=>$up_proid){
                                $buynum += Db::name('shop_order_goods')->where('aid',$aid)->where('mid',$mid)->where('proid',$up_proid)->whereIn('orderid',$have_orderids)->where('status','in','1,2,3')->sum('num');
                                if($buynum >= $pronum){
                                    $isextend = true;
                                }
                            }
                        }
                        //满足条件，累加延长等级时间
                        if($isextend){
                            $levelendtime = $member['levelendtime'] + 86400 * $nowlv['yxqdate'];
                            //todo 判断是否默认分组
                            Db::name('member')->where('aid', $aid)->where('id', $mid)->update(['levelendtime' => $levelendtime]);
                            $order = [
                                'aid' => $aid,
                                'mid' => $mid,
                                'from_mid' => $mid,
                                'pid' => $member['pid'],
                                'levelid' => $nowlv['id'],
                                'title' => '复购延期',
                                'totalprice' => 0,
                                'createtime' => time(),
                                'levelup_time' => time(),
                                'beforelevelid' => $nowlv['id'],
                                'form0' => '类型^_^购买商品延长等级',
                                'platform' => platform,
                                'status' => 2
                            ];
                            Db::name('member_levelup_order')->insert($order);
                        }
                    }
                }
            }
            if(getcustom('levelup_pro_keep_time') && $nowlv['up_pro_keep_time'] == 1 && $nowlv['up_pro_extend_time'] == 0){
                //不升级，判断是否保持有效期（购买时间+有效期天数=过期时间），通过member_levelup_order的时间对比订单时间
                //注意两种方式不可同时开启
                if($nowlv['yxqdate'] > 0){
                    $isextend = false;
                    $last_levelup_order = Db::name('member_levelup_order')->where('aid',$aid)->where('mid',$mid)->where('levelid',$nowlv['id'])->order('createtime','desc')->find();
                    $have_orderids = Db::name('shop_order')->where('aid',$aid)->where('mid',$mid)->where('createtime','>',$last_levelup_order['createtime'])->whereIn('status',[1,2,3])->column('id');
                    if($have_orderids){
                        $up_proids = explode(',',str_replace('，',',',$nowlv['up_proid']));
                        $up_pronums = explode(',',str_replace('，',',',$nowlv['up_pronum']));
                        if(count($up_pronums) > 1) {
                            foreach($up_proids as $k=>$up_proid){
                                $pronum = $up_pronums[$k];
                                if(!$pronum) $pronum = 1;
                                $buynum = Db::name('shop_order_goods')->where('aid',$aid)->where('mid',$mid)->where('proid',$up_proid)->whereIn('orderid',$have_orderids)->where('status','in','1,2,3')->sum('num');
                                if($buynum >= $pronum){
                                    $isextend = true;
                                }
                            }
                        } else {
                            $pronum = $up_pronums[0];
                            if(!$pronum) $pronum = 1;
                            $buynum = 0;
                            foreach($up_proids as $k=>$up_proid){
                                $buynum += Db::name('shop_order_goods')->where('aid',$aid)->where('mid',$mid)->where('proid',$up_proid)->whereIn('orderid',$have_orderids)->where('status','in','1,2,3')->sum('num');
                                if($buynum >= $pronum){
                                    $isextend = true;
                                }
                            }
                        }
                        //满足条件，保持等级时间
                        if($isextend){
                            $levelendtime = time() + 86400 * $nowlv['yxqdate'];
                            //todo 判断是否默认分组
                            Db::name('member')->where('aid', $aid)->where('id', $mid)->update(['levelendtime' => $levelendtime]);
                            $order = [
                                'aid' => $aid,
                                'mid' => $mid,
                                'from_mid' => $mid,
                                'pid' => $member['pid'],
                                'levelid' => $nowlv['id'],
                                'title' => '复购延期',
                                'totalprice' => 0,
                                'createtime' => time(),
                                'levelup_time' => time(),
                                'beforelevelid' => $nowlv['id'],
                                'form0' => '类型^_^购买商品延长等级',
                                'platform' => platform,
                                'status' => 2
                            ];
                            Db::name('member_levelup_order')->insert($order);
                        }
                    }
                }
            }
        }
    }
    //处理升级操作
    public static function handleUpLevel($aid,$mid,$newlv,$levelInfo,$member,$cid){
        if($newlv && $newlv['id'] != $levelInfo['levelid']) {
            Log::write([
                'file'=>__FILE__,
                'line'=>__LINE__,
                'handleUpLevel member'=>jsonEncode($member),
                'newlevel'=>jsonEncode($newlv)
            ]);
            if ($newlv['yxqdate'] > 0) {
                $levelendtime = strtotime(date('Y-m-d')) + 86400 + 86400 * $newlv['yxqdate'];
            } else {
                $levelendtime = 0;
            }
            //判断是否默认分组
            if($newlv['cid'] > 0)
                $is_default = Db::name('member_level_category')->where('id', $newlv['cid'])->value('isdefault');
            if ($is_default || $newlv['cid'] == 0) {
                $update = ['levelid' => $newlv['id'], 'levelendtime' => $levelendtime,'levelstarttime' => time()];
//                if(getcustom('coupon_xianxia_buy')){
//                    $update['is_zt_up'] = 0; 
//                }
                Db::name('member')->where('aid', $aid)->where('id', $mid)->update($update);
            } else {
                if (getcustom('plug_sanyang')) {
                    $count = Db::name('member_level_record')->where('aid', $aid)->where('mid', $mid)->where('cid', $newlv['cid'])->count();
                    if($count) Db::name('member_level_record')->where('aid', $aid)->where('mid', $mid)->where('cid', $newlv['cid'])->update(['levelid' => $newlv['id'], 'levelendtime' => $levelendtime]);
                    else {
                        $record_data = ['levelid' => $newlv['id'], 'levelendtime' => $levelendtime];
                        $record_data['aid'] = $aid;
                        $record_data['mid'] = $mid;
                        $record_data['createtime'] = time();
                        $record_data['cid'] = $newlv['cid'];
                        Db::name('member_level_record')->insertGetId($record_data);
                    }
                    Db::name('member_level_record')->where('aid', $aid)->where('mid', $mid)->where('cid', $newlv['cid'])->update(['levelstarttime' => time()]);
                }
            }

            Wechat::updatemembercard($aid, $mid);
            //赠送积分
            if($newlv['up_give_score'] > 0) {
                self::addscore($aid, $mid, $newlv['up_give_score'], '升级奖励');
            }
            //奖励佣金
            if($newlv['up_give_commission'] > 0) {
                self::addcommission($aid,$mid,0,$newlv['up_give_commission'],'升级奖励');
            }
            //奖励余额
            if($newlv['up_give_money'] > 0) {
                self::addmoney($aid,$mid,$newlv['up_give_money'],'升级奖励');
            }
            //赠送上级佣金
            if($newlv['up_give_parent_money'] > 0 && $member['pid']) {
                if(getcustom('coupon_xianxia_buy')){
                    $next_level = Db::name('member_level')->where('aid',$aid)->where('sort','>',$newlv['sort'])->order('sort asc')->find();
                    if($next_level){
                        self::addcommission($aid, $member['pid'], $mid, $newlv['up_give_parent_money'], '直推奖');
                    }
                }else{
                    self::addcommission($aid, $member['pid'], $mid, $newlv['up_give_parent_money'], '直推奖');
                }
            }

            if($newlv['up_give_parent_coupon_ids'] && $newlv['up_give_parent_coupon_nums'] && $member['pid']){
                $coupon_ids = explode(',',$newlv['up_give_parent_coupon_ids']);
                $coupon_nums = explode(',',$newlv['up_give_parent_coupon_nums']);
                if($coupon_ids){
                    foreach($coupon_ids as $ck=>$coupon_id){
                        if(!$coupon_nums[$ck]){
                            $coupon_nums[$ck] = 1;
                        }
                        for($i=0;$i<$coupon_nums[$ck];$i++){
                            \app\common\Coupon::send($aid,$member['pid'],$coupon_id,true);
                        }
                    }
                }
            }

            //升级赠送优惠券
            if(getcustom('up_give_coupon')){
                //商城优惠券赠送
                $shop_coupon = $newlv['up_give_coupon']?json_decode($newlv['up_give_coupon'],true):[];
                foreach($shop_coupon as $k=>$v){
                    if($v['num']<1){
                        continue;
                    }
                    for($i=0;$i<$v['num'];$i++){
                        \app\common\Coupon::send($aid,$member['id'],$v['id'],true);
                    }
                }
                //餐饮优惠券赠送
                $restaurant_coupon = $newlv['up_give_restaurant_coupon']?json_decode($newlv['up_give_restaurant_coupon'],true):[];
                foreach($restaurant_coupon as $k=>$v){
                    if($v['num']<1){
                        continue;
                    }
                    for($i=0;$i<$v['num'];$i++){
                        \app\common\Coupon::send($aid,$member['id'],$v['id'],true);
                    }
                }
            }

            if(getcustom('up_giveparent') && $newlv['up_giveparent_num'] > 0 /*&& $member['pid']*/){ //升级后 他直推的几个人留给他的上级
                //文档 https://doc.weixin.qq.com/doc/w3_AT4AYwbFACwly20n4PhQXGIkzEGvk?scode=AHMAHgcfAA0QNhPwm4AT4AYwbFACw
                $whereup = [];
                $whereup[] = ['aid', '=', $aid];
                $whereup[] = ['pid', '=', $mid];
                if($newlv['up_giveparent_levelid']){
                    //指定等级,多个英文逗号分隔
                    $newlv['up_giveparent_levelid'] = explode(',',$newlv['up_giveparent_levelid']);
                    $whereup[] = ['levelid', 'in', $newlv['up_giveparent_levelid']];
                }
                $downmemberlist = Db::name('member')->where($whereup)->limit($newlv['up_giveparent_num'])->order('id')->select()->toArray();
                if($downmemberlist){
                    $newlv['up_giveparent_levelid_p'] = trim($newlv['up_giveparent_levelid_p']);
                    $newlv_up_giveparent_levelid_arr = explode(',',$newlv['up_giveparent_levelid_p']);
                    Log::write([
                        'file'=>__FILE__,
                        'line'=>__LINE__,
                        'levelidp'=>$newlv_up_giveparent_levelid_arr,
                        'downmemberlist'=>jsonEncode($downmemberlist)
                    ]);
                    foreach($downmemberlist as $downmember){
                        //升级后 他直推的几个人留给他的上级，原推荐人不改变
                        $downmember_level = Db::name('member_level')->where('id',$downmember['levelid'])->field('id,up_change_back')->find();
                        //如同时符合“升级给上级人数”和“升级后回归”，则不脱离，直接回归
                        if($downmember_level['up_change_back'] == 1) {
                            Log::write([
                                'file'=>__FILE__,
                                'error'=>'同时符合“升级给上级人数”和“升级后回归”，则不脱离，直接回归'
                            ]);
                            continue;
                        }
                        //指定上级是默认上级还是指定等级的上级
                        if(!empty($newlv['up_giveparent_levelid_p']) && !empty($newlv_up_giveparent_levelid_arr)){
                            //如果指定了等级，他的所有上级都不在指定的等级范围内，则留给平台
                            $newpid = 0;
                            if($member['path']){
                                $parentList = Db::name('member')->whereIn('levelid',$newlv_up_giveparent_levelid_arr)->where('aid',$aid)->where('id','in',$member['path'])->order(Db::raw('field(id,'.$member['path'].')'))->select()->toArray();
                                if($parentList){
                                    $nearP = end($parentList);
                                    $newpid = $nearP['id'];
                                }
                            }
                        }else{
                            $newpid = $member['pid'];
                        }
                        $updatem = ['id'=>$downmember['id'],'pid'=>$newpid,'change_pid_time'=>time()];
                        if(!$downmember['pid_origin']){
                            $updatem['pid_origin'] = $downmember['pid'];
                            $updatem['path_origin'] = $downmember['path'];
                        }
                        \app\model\Member::edit($aid,$updatem);//todo
                        $insertLog = ['aid'=>$aid,'mid'=>$downmember['id'],'pid'=>$newpid,'createtime'=>time()];
                        if($downmember['pid_origin']){
                            $insertLog['pid_origin'] = $downmember['pid_origin'];
                            $insertLog['path_origin'] = $downmember['path_origin'];
                        }else{
                            $insertLog['pid_origin'] = $downmember['pid'];
                            $insertLog['path_origin'] = $downmember['path'];
                        }
                        Db::name('member_pid_changelog')->insert($insertLog);
                    }
                }
            }

            if(getcustom('up_change_pid')){
                //升级后脱离上级，推荐人为空
                if($newlv['up_change_pid'] == 1 && $member['pid']) {
                    //原推荐人不改变
                    $updatem = ['id'=>$mid,'pid'=>0,'change_pid_time'=>time()];
                    if(!$member['pid_origin']){
                        $updatem['pid_origin'] = $member['pid'];
                        $updatem['path_origin'] = $member['path'];
                    }
                    Log::write([
                        'file'=>__FILE__,
                        'line'=>__LINE__,
                        'edit'=>$updatem
                    ]);
                    \app\model\Member::edit($aid,$updatem);
                    $insertLog = ['aid'=>$aid,'mid'=>$mid,'pid'=>0,'createtime'=>time()];
                    if($member['pid_origin']){
                        $insertLog['pid_origin'] = $member['pid_origin'];
                        $insertLog['path_origin'] = $member['path_origin'];
                    }else{
                        $insertLog['pid_origin'] = $member['pid'];
                        $insertLog['path_origin'] = $member['path'];
                    }
                    Db::name('member_pid_changelog')->insert($insertLog);
                }
                //升级后回归到以前的推荐人下面（仅脱离的人生效）
                if($newlv['up_change_back'] == 1 && $member['pid_origin']){
                    Log::write([
                        'file'=>__FILE__,
                        'line'=>__LINE__,
                        'member[pid_origin]'=>$member['pid_origin']
                    ]);
                    //230909 pid_origin=0改为pid_origin=null
                    \app\model\Member::edit($aid,['id'=>$mid,'pid'=>$member['pid_origin'],'pid_origin'=>null,'path_origin'=>'','change_pid_time'=>time()]);
                    Db::name('member_pid_changelog')->where('aid',$aid)->where('mid',$mid)->where('pid_origin',$member['pid_origin'])->update(['isback'=>1,'updatetime'=>time()]);
                }
            }

            if(getcustom('commission_frozen')){
                //扶持金解冻冻结
                $admin = Db::name('admin')->where('id',$aid)->find();
                $unfrozen_mid_arr = [];
                $unfrozen1_mids = [];
                $unfrozen2_mids = [];
                $unfrozen3_mids = [];
                $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
                if($admin['commission_frozen'] == 1 && ($member['pid'] || $member['pid_origin'])){
                    $set = Db::name('admin_set')->where('aid',$aid)->find();
                    $frozen_type = explode(',',$set['fuchi_unfrozen']);
                    //1 伞下x个,等级ID为x的会员（等级ID多个使用英文逗号间隔）
                    //2 直推脱离的会员等级ID升级为x（等级ID多个使用英文逗号间隔）
                    //3 直推会员等级ID升级为x（等级ID多个使用英文逗号间隔）
                    //解冻方式 fuchi_unfrozen_type 1全部(判断条件1和2)，2单线（判断条件1和3）
                    if($frozen_type){
                        $fuchi_unfrozen1_levelidArr = explode(',',$set['fuchi_unfrozen1_levelid']);
                        if(in_array(1,$frozen_type) && in_array($newlv['id'],$fuchi_unfrozen1_levelidArr) && $set['fuchi_unfrozen1_num'] > 0){
                            //存在多个上级同时解冻
                            $parentList = Db::name('member')->field('id,nickname,pid,path,commission_frozen_status')->where('id','in',$member['path'])->where('commission_frozen_status',0)->select()->toArray();
                            foreach($parentList as $parent){
                                $children = self::getdownmids($aid,$parent['id'],0,$set['fuchi_unfrozen1_levelid']);
                                if(count($children) >= $set['fuchi_unfrozen1_num']) {
                                    $unfrozen1_mids[] = $parent['id'];
                                }
                            }
                        }

                        $fuchi_unfrozen2_levelidArr = explode(',',$set['fuchi_unfrozen2_levelid']);
                        //直推脱离的所有会员等级ID升级为x,原父级解冻
                        if($set['fuchi_unfrozen_type']==1 && in_array(2,$frozen_type) && in_array($newlv['id'],$fuchi_unfrozen2_levelidArr)){
                            if($member['pid_origin']){
                                $origin_commission_frozen_status = Db::name('member')->field('id,nickname,pid,path,commission_frozen_status')->where('id',$member['pid_origin'])->value('commission_frozen_status');
                                if(!$origin_commission_frozen_status){
                                    $children = Db::name('member')->where('aid',$aid)->where('pid_origin',$member['pid_origin'])->select()->toArray();
                                    $num_ok = 0;
                                    foreach ($children as $citem){
                                        if(in_array($citem['levelid'],$fuchi_unfrozen2_levelidArr)){
                                            $num_ok++;
                                        }
                                    }
                                    if(count($children) == $num_ok) $unfrozen2_mids[] = $member['pid_origin'];
                                }
                            }else{
                                //升级后回归的会员，230424增加记录表，如不兼容老数据可只判断member_pid_changelog表，无需member表
                                $changelog = Db::name('member_pid_changelog')->where('aid',$aid)->where('mid',$mid)->where('pid_origin',$member['pid'])->find();
                                if($changelog['isback'] == 1){
                                    $origin_commission_frozen_status = Db::name('member')->field('id,nickname,pid,path,commission_frozen_status')->where('id',$member['pid'])->value('commission_frozen_status');
                                    if(!$origin_commission_frozen_status){
                                        $children = Db::name('member')->where('aid',$aid)->where('pid_origin',$member['pid'])->select()->toArray();
                                        $childrenbackMids = Db::name('member_pid_changelog')->where('aid',$aid)->where('pid_origin',$member['pid'])->where('isback',1)->column('mid');
                                        $childrenback = Db::name('member')->where('aid',$aid)->whereIn('id',$childrenbackMids)->select()->toArray();
                                        $num_ok = 0;
                                        foreach ($children as $citem){
                                            if(in_array($citem['levelid'],$fuchi_unfrozen2_levelidArr)){
                                                $num_ok++;
                                            }
                                        }
                                        foreach ($childrenback as $citem){
                                            if(in_array($citem['levelid'],$fuchi_unfrozen2_levelidArr)){
                                                $num_ok++;
                                            }
                                        }
                                        if((count($children) + count($childrenback)) == $num_ok) $unfrozen2_mids[] = $member['pid'];
                                    }
                                }
                            }
                        }
                        $fuchi_unfrozen3_levelidArr = explode(',',$set['fuchi_unfrozen3_levelid']);
                        if($set['fuchi_unfrozen_type']==2 && in_array(3,$frozen_type) && in_array($newlv['id'],$fuchi_unfrozen3_levelidArr)){
                            $unfrozen_pid = $member['pid_origin'] ? $member['pid_origin'] : $member['pid'];
                            $unfrozen3_mids[] = $unfrozen_pid;
                        }
                        //解冻方式 fuchi_unfrozen_type 1全部(判断条件1和2)，2单线（判断条件1和3）
                        if($set['fuchi_unfrozen_type']==1){
                            if(in_array(1,$frozen_type) && in_array(2,$frozen_type)){
                                $unfrozen_mid_arr = array_intersect($unfrozen1_mids,$unfrozen2_mids);
                            }else{
                                if(in_array(1,$frozen_type)){
                                    $unfrozen_mid_arr = $unfrozen1_mids;
                                }
                                if(in_array(2,$frozen_type)){
                                    $unfrozen_mid_arr = $unfrozen2_mids;
                                }
                            }
                            //解冻
                            self::unfrozenMoney($aid,$unfrozen_mid_arr);
                        }elseif($set['fuchi_unfrozen_type']==2){
                            if(in_array(1,$frozen_type) && in_array(3,$frozen_type)){
                                $unfrozen_mid_arr = array_intersect($unfrozen1_mids,$unfrozen3_mids);
                            }else{
                                if(in_array(1,$frozen_type)){
                                    $unfrozen_mid_arr = $unfrozen1_mids;
                                }
                                if(in_array(3,$frozen_type)){
                                    $unfrozen_mid_arr = $unfrozen3_mids;
                                }
                            }
                            //解冻
                            self::unfrozenMoney($aid,$unfrozen_mid_arr, $mid);
                        }
                    }
                }
            }

            if(getcustom('fenhong_jiaquan_bylevel')){
                if($newlv['fenhong_copies']){
                    \app\common\Member::addfhcopies($aid,$mid,$newlv['fenhong_copies'],'升级奖励');
                    Db::name('member_fenhong_jiaquan')->insert([
                        'aid' => $aid,
                        'mid' => $mid,
                        'type' => 'uplevel',
                        'remark' => '升级奖励',
                        'createtime' => time(),
                        'effect_time' => time(),
                        'jiesuan_time' => time(),
                        'status' => 2,//已结算
                        'copies' => $newlv['fenhong_copies'],
                    ]);
                }
            }

            Log::write([
                'file'=>__FILE__,
                'line'=>__LIne__,
                'mid'=>$mid,
                'newlvid'=>$newlv['id']
            ]);

            //升级记录
            $order = [
                'aid' => $aid,
                'mid' => $mid,
                'from_mid' => $mid,
                'pid' => $member['pid'],
                'levelid' => $newlv['id'] ,
                'title' => '自动升级',
                'totalprice' => 0,
                'createtime' => time(),
                'levelup_time' => time(),
                'beforelevelid' => $levelInfo['levelid'],
                'form0' => '类型^_^自动升级',
                'platform' => platform,
                'status' => 2,
            ];
            //自动降级，记录是否检测降级状态，并更新之前的升级记录不再检测
            if(getcustom('level_auto_down')){
                Db::name('member_levelup_order')->where('mid',$mid)->update(['check_down'=>1]);
                $order['check_down'] = 0;
            }
            Db::name('member_levelup_order')->insert($order);
            $tmplcontent = [];
            $tmplcontent['first'] = '恭喜您成功升级为'.$newlv['name'];
            $tmplcontent['remark'] = '点击进入查看~';
            $tmplcontent['keyword1'] = $newlv['name']; //会员等级
            $tmplcontent['keyword2'] = '已生效';//审核状态
            $rs = \app\common\Wechat::sendtmpl($aid,$mid,'tmpl_uplv',$tmplcontent,m_url('pages/my/usercenter', $aid));

            if(getcustom('levelupifdownup') && $member['path']){
                $levelArr = Db::name('member_level')->where('aid',$aid)->where('cid', $cid)->order('sort,id')->column('sort','id');
                $parentList = Db::name('member')->where('id','in',$member['path'])->select()->toArray();
                foreach($parentList as $parent){
                    if($levelArr[$parent['levelid']] < $levelArr[$newlv['id']]){
                        Db::name('member')->where('aid', $aid)->where('id', $parent['id'])->update(['levelid' => $newlv['id'], 'levelendtime' => $levelendtime]);
                    }
                }
            }
        }
    }

    public static function unfrozenMoney($aid,$unfrozen_mid_arr,$from_mid=0)
    {
        if(getcustom('commission_frozen')){
            $unfrozen_mid_arr = array_unique($unfrozen_mid_arr);
            if($from_mid){
                //单线
                $children = self::getdownmids($aid,$from_mid,0);
                $children[] = $from_mid;
                $children[] = 0;
                foreach ($unfrozen_mid_arr as $mid){
                    $frozen_record = Db::name('member_fuchi_record')->where('aid',$aid)->where('mid',$mid)->where('frommid','in',$children)->where('status',0)->select()->toArray();
                    foreach ($frozen_record as $v){
                        self::addFuchi($aid,$v['mid'],$v['frommid'],$v['commission']*-1,'解冻');
                        self::addcommission($aid, $v['mid'], $v['frommid'], $v['commission'], '解冻',1,'unfrozen');
                    }
                    Db::name('member_fuchi_record')->where('aid',$aid)->where('mid',$mid)->where('frommid','in',[$from_mid,0])->where('status',0)->update(['status'=>1,'endtime'=>time()]);
                }
            }else{
                foreach ($unfrozen_mid_arr as $mid){
                    Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['commission_frozen_status'=>1]);
                    $frozen_record = Db::name('member_fuchi_record')->where('aid',$aid)->where('mid',$mid)->where('status',0)->select()->toArray();
                    foreach ($frozen_record as $v){
                        self::addFuchi($aid,$v['mid'],$v['frommid'],$v['commission']*-1,'解冻');
                        self::addcommission($aid, $v['mid'], $v['frommid'], $v['commission'], '解冻',1,'unfrozen');
                    }
                    Db::name('member_fuchi_record')->where('aid',$aid)->where('mid',$mid)->where('status',0)->update(['status'=>1,'endtime'=>time()]);
                }
            }
        }
    }

    //加余额
    public static function addmoney($aid,$mid,$money,$remark,$frommid=0,$paytype=''){
        if($money==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        if(getcustom('w7moneyscore')) {
            $w7moneyscore = db('admin_set')->where(['aid'=>$aid])->value('w7moneyscore');
            if($w7moneyscore == 1){
                return self::addw7moneyscore($aid,$member,2,$money,$remark);
            }else{
                $after = $member['money'] + $money;
                Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['money'=>$after]);
            }
        } else {
            $after = $member['money'] + $money;
            Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['money'=>$after]);
        }

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['money'] = $money;
        $data['after'] = $after;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        $data['paytype'] = $paytype;
        if(getcustom('money_transfer') || getcustom('money_friend_transfer')) {
            $data['from_mid'] = $frommid;
        }
        Db::name('member_moneylog')->insert($data);
        self::uplv($aid,$mid);
        Wechat::updatemembercard($aid,$mid);

		$tmplcontent = [];
		$tmplcontent['first'] = '您的'.t('余额').'发生变动，变动金额：'.$money;
		$tmplcontent['remark'] = '点击进入查看~';
		$tmplcontent['keyword1'] = date('Y-m-d H:i'); //变动时间
		$tmplcontent['keyword2'] = $remark;  //变动类型
		$tmplcontent['keyword3'] = (string) round($money,2);  //变动金额
		$tmplcontent['keyword4'] = (string) round($after,2);  //当前余额
        $tmplcontentNew = [];
        $tmplcontentNew['thing2'] = str_replace(',','',mb_substr($remark,0,5));//消费项目
        $tmplcontentNew['amount3'] = round($money,2);//消费金额
        $tmplcontentNew['amount4'] = round($after,2);//卡内余额
        $tmplcontentNew['time6'] = date('Y-m-d H:i'); //变动时间
		$rs = \app\common\Wechat::sendtmpl($aid,$mid,'tmpl_moneychange',$tmplcontent,m_url('pages/my/usercenter', $aid),$tmplcontentNew);
         //变动通知
        if(getcustom('sms_temp_money_use')){
            if($member['tel'] && $money < 0){
                $rs = \app\common\Sms::send($aid,$member['tel'],'tmpl_money_use',['money'=>$money,'real_money'=>$money,'sy_money'=>$after]);
            }
        }
        return ['status'=>1,'msg'=>''];
    }
    //加积分
    //@update 22-7-21 增加渠道
    public static function addscore($aid,$mid,$score,$remark,$channel='',$bid=0,$frommid=0,$addtotal=1){
        if($score==0) return ;
        $score_weishu = 0;
        if(getcustom('score_weishu')){
            $score_weishu = Db::name('admin_set')->where('aid',$aid)->value('score_weishu');
            $score = dd_money_format($score,$score_weishu);
        }
        if($score_weishu==0){
            $score = intval($score);
        }

        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];
		if(getcustom('andun_jiuxuan') && $member['levelid'] == 5){
			return ['status'=>0,'msg'=>'该等级不能获取积分'];
		}

        $member['score'] = self::getscore($member);
        if($score < 0 && $member['score'] < $score*-1) {
            if($remark == '过期扣除'){
                $score = $member['score'] *-1;
            }else{
                return ['status'=>0,'msg'=>t('积分').'不足'];
            }
        }

        $updata = [];
        $after = $member['score'] + $score;
        $updata['score'] = $after;

        $totalscore = $member['totalscore']?$member['totalscore']:0;
        //如果已定时任务执行统计过累计积分，且积分大于0，则走累计积分
        if($member['iscountscore'] && $score > 0 && $addtotal==1){
            $totalscore = $totalscore + $score;
        }
        $updata['totalscore'] = $totalscore;

        if(getcustom('w7moneyscore')) {
            $w7moneyscore = db('admin_set')->where(['aid'=>$aid])->value('w7moneyscore');
            if($w7moneyscore == 1){
                return self::addw7moneyscore($aid,$member,1,$score,$remark);
            }else{
                Db::name('member')->where('aid',$aid)->where('id',$mid)->update($updata);
            }
        } else {
            Db::name('member')->where('aid',$aid)->where('id',$mid)->update($updata);
        }

        $data = [];
        $data['aid'] = $aid;
        $data['bid'] = $bid;
        $data['mid'] = $mid;
        $data['score'] = $score;
        $data['after'] = $after;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        $data['type'] = 1;
        $data['channel'] = $channel;
        $data['status'] = ($remark == '过期扣除') ? -1 : 0;
        $data['is_cancel'] = ($remark == '撤销操作') ? 1 : 0;
        if(getcustom('score_transfer') || getcustom('score_friend_transfer')) {
            $data['from_mid'] = $frommid;
        }
        Db::name('member_scorelog')->insert($data);
        Wechat::updatemembercard($aid,$mid,$remark);

        if($score < 0 && $remark != '撤销操作' && $remark != '过期扣除'){
            $score2 = $score*-1;
            $loglist = Db::name('member_scorelog')->where('aid',$aid)->where('mid',$mid)->where('score','>',0)
                ->where('status',0)->where('is_cancel',0)->order('createtime','asc')->select()->toArray();
            foreach ($loglist as $item){
                if($item['score'] - $item['used'] <= $score2){
                    Db::name('member_scorelog')->where('id',$item['id'])->update(['used'=>$item['score'],'status'=>1]);
                }else{
                    Db::name('member_scorelog')->where('id',$item['id'])->update(['used'=>$item['used']+$score2]);
                    break;
                }
                $score2 = $score2 - ($item['score'] - $item['used']);
            }
        }

		if(getcustom('business_selfscore') && $bid ==0){
			Db::name('admin')->where('id',$aid)->inc('score',-$score)->update();
			$data = [];
			$data['aid'] = $aid;
			$data['score'] = -$score;
			$data['after'] = Db::name('admin')->where('id',$aid)->value('score');
			$data['createtime'] = time();
			if($score > 0){
				$data['remark'] = '给用户'.$member['nickname'].'加'.t('积分');
			}else{
				$data['remark'] = '用户'.$member['nickname'].'花费'.t('积分');
			}
			Db::name('admin_scorelog')->insert($data);
		}

        return ['status'=>1,'msg'=>''];
    }

    //积分过期
    public static function scoreExpire(){
        if(getcustom('score_expire')){
            $admin_setlist = Db::name('admin_set')->where('score_expire_status','=',1)->where('score_expire_days','>',0)->column('aid,score_expire_status,score_expire_days','aid');
            $time = time();
            foreach($admin_setlist as $set){
                $scoreloglist = Db::name('member_scorelog')->where('aid',$set['aid'])->where('status',0)->where('is_cancel',0)->where('score','>',0)
                    ->where('createtime','<',$time - $set['score_expire_days'] * 86400)->select()->toArray();
                foreach ($scoreloglist as $item){
                    Db::name('member_scorelog')->where('id',$item['id'])->update(['expire_time'=>$time,'status'=>-1]);
                    $expirScore = ($item['score']-$item['used']) * -1;//过期积分=获得积分-已用积分
                    self::addscore($item['aid'],$item['mid'],$expirScore,'过期扣除');
                }
            }
        }
    }

    public static function addgongxian($aid,$mid,$value,$remark,$channel='',$orderid=0){
        if(getcustom('member_gongxian')){
            if($value==0) return ;
            $value = intval($value);
            $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
            if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

            if($value < 0 && $member['gongxian'] < $value*-1) return ['status'=>0,'msg'=>t('贡献').'不足'];

            $after = $member['gongxian'] + $value;
            Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['gongxian'=>$after]);

            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $mid;
            $data['value'] = $value;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            $data['channel'] = $channel;
            $data['orderid'] = $orderid;
            Db::name('member_gongxianlog')->insert($data);
            return ['status'=>1,'msg'=>''];
        }
    }
    //加提现积分
    public static function addscore_withdraw($aid,$mid,$score,$remark){
        if($score==0) return ;
        $score = intval($score);
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];
        if($score < 0 && $member['score_withdraw'] < $score*-1) return ['status'=>0,'msg'=>t('积分').'不足'];

        $after = $member['score_withdraw'] + $score;
        Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['score_withdraw'=>$after]);

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['score'] = $score;
        $data['after'] = $after;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        $data['type'] = 2;
        Db::name('member_scorelog')->insert($data);
        return ['status'=>1,'msg'=>''];
    }
    //加佣金

    /**
     * @param $aid
     * @param $mid
     * @param $frommid
     * @param $commission
     * @param $remark
     * @param $addtotal
     * @param $fhtype 类型 枚举值 'unfrozen'解冻,'withdraw_back'提现退回,admin管理员修改
     * @return array|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function addcommission($aid,$mid,$frommid=0,$commission=0,$remark='',$addtotal=1,$fhtype=''){
        if($commission==0) return ;
        $real_commission = $commission;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();

        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        $set = Db::name('admin_set')->where('aid',$aid)->find();

        if(getcustom('commission_service_fee')){
            if($set['commission_service_fee'] > 0 && $commission > 0 && !in_array($fhtype, ['unfrozen','withdraw_back','admin'])){
                //平台服务费
                $commission_service_fee = round($set['commission_service_fee'] * $commission / 100,2);
                $commission -= $commission_service_fee;
            }
        }

		if($commission > 0 && $set['commission2scorepercent'] > 0){
			$oldcommission = $commission;
			$commission = round($commission * (1-$set['commission2scorepercent']*0.01),2);
			$score = $oldcommission - $commission;
			self::addscore($aid,$mid,$score,$remark);
		}

        if(getcustom('commission_frozen')){
            if($commission > 0 && !in_array($fhtype, ['unfrozen','withdraw_back'])){
                //扶持金冻结
                $fuchi_levelids = explode(',',$set['fuchi_levelids']);
                if(in_array(-1,$fuchi_levelids) || in_array($member['levelid'],$fuchi_levelids)){
                    $admin = Db::name('admin')->where('id',$aid)->find();
                    if($admin['commission_frozen'] == 1 && $set['fuchi_percent'] > 0 && $set['fuchi_percent'] <= 100 && !$member['commission_frozen_status']){
                        $fuchi_money = round($set['fuchi_percent'] * $commission / 100,2);
                        $commission -= $fuchi_money;
                        self::addFuchi($aid,$mid,$frommid,$fuchi_money,$remark);
                        Db::name('member_fuchi_record')->insert(['aid'=>$aid,'mid'=>$mid,'frommid'=>$frommid,'orderid'=>0,'ogid'=>0,'type'=>'',
                            'commission'=>$fuchi_money,'score'=>0,'remark'=>$remark,'createtime'=>time()]);
                    }
                }
            }
        }
        if(getcustom('commission_xiaofei')){
            if($commission > 0 && !in_array($fhtype, ['unfrozen','withdraw_back'])){
                //佣金金冻结
                $frozen_levelids = explode(',',$set['xiaofei_levelids']);
                if(in_array(-1,$frozen_levelids) || in_array($member['levelid'],$frozen_levelids)){
                    if($set['xiaofei_percent'] > 0 && $set['xiaofei_percent'] <= 100){
                        $xiaofei_money = round($set['xiaofei_percent'] * $commission / 100,2);
                        $commission -= $xiaofei_money;
                        self::addXiaofei($aid,$mid,$frommid,$xiaofei_money,$remark);

                    }
                }
            }
        }
        // 等级限制 达到奖励上限不再发放任何佣金，0表示不限制
        if(getcustom('commission_max')){
            $m_level_com = Db::name('member_level')->where('id',$member['levelid'])->value('commission_max');
            if($m_level_com > 0){
                $m_total = $member['totalcommission'];
                if($m_total >= $m_level_com){
                    return ['status'=>0,'msg'=>t('佣金').'已达上限！'];
                }
                $com = $m_level_com - $m_total;
                if($com <= $commission){
                    $commission = $com;
                }
            }
        }
	

		
        if($commission > 0 && $addtotal==1){
            $totalcommission = $member['totalcommission'] + $commission;
        }else{
            $totalcommission = $member['totalcommission'];
        }
        $after = $member['commission'] + $commission;
        $update_member = ['totalcommission'=>$totalcommission,'commission'=>$after];
        if($fhtype == 'fenhong') {
            $update_member['total_fenhong_partner'] = $member['total_fenhong_partner'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        } elseif($fhtype == 'teamfenhong') {
            $update_member['total_fenhong_team'] = $member['total_fenhong_team'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        } elseif($fhtype == 'level_teamfenhong') {
            $update_member['total_fenhong_level_team'] = $member['total_fenhong_level_team'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        } elseif($fhtype == 'areafenhong') {
            $update_member['total_fenhong_area'] = $member['total_fenhong_area'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        }elseif($fhtype == 'touzi_fenhong') {
            $update_member['total_fenhong_touzi'] = $member['total_fenhong_touzi'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        }elseif($fhtype == 'gongxian_fenhong'){
            $update_member['total_fenhong_gongxian'] = $member['total_fenhong_gongxian'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        }elseif($fhtype == 'fenhong_huiben') {
            $update_member['total_fenhong_huiben'] = bcadd($member['total_fenhong_huiben'] , $real_commission,2);
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        }
        if(getcustom('product_baodan')){
            //如果总佣金大于上限值,减去佣金，并且加 冻结
            if($update_member['totalcommission'] > $member['baodan_max'] && $addtotal==1  && $commission>0){
                $update_member['totalcommission'] = $update_member['totalcommission'] - $commission;
                $update_member['commission'] = $update_member['commission'] - $commission;
                //加冻结
                $totalfreeze =$member['baodan_freeze'] + $commission;
                $update_member['baodan_freeze']  = $totalfreeze;
                //加记录
                $baodan_data = [];
                $baodan_data['aid'] = $aid;
                $baodan_data['mid'] = $mid;
                $baodan_data['commission'] = $commission;
                $baodan_data['after'] = $totalfreeze;
                $baodan_data['createtime'] = time();
                $baodan_data['remark'] = $remark;
                Db::name('member_baodan_freeze_log')->insert($baodan_data);
            }
        }
        Db::name('member')->where('aid',$aid)->where('id',$mid)->update($update_member);

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['frommid'] = $frommid;
        $data['commission'] = $commission;
        $data['after'] = $after;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        if($fhtype) $data['fhtype'] = $fhtype;
        $data['service_fee'] = $commission_service_fee > 0 ? $commission_service_fee : 0;
        Db::name('member_commissionlog')->insert($data);
		
		if(getcustom('commission_autowithdraw')){
			if($commission>0 && strpos($remark,'后台修改：')!==0){
				$commission_autowithdraw = $set['commission_autowithdraw'];
				if($commission_autowithdraw == 1){ //佣金自动打款
					$rs = \app\common\Wxpay::transfers($aid,$mid,$commission,'','',$remark);
					if($rs && $rs['status']==1){ //打款成功
						self::addcommission($aid,$mid,'',-$commission,'佣金打款成功');
					}else{
						Log::write('自动打款失败--'.$commission);
						Log::write($rs);
					}
				}
			}
		}
		
		if(getcustom('forcerebuy') && $commission > 0){
			$forcerebuyList = Db::name('forcerebuy')->where('aid',$aid)->where('type',0)->where('status',1)->where('commission','<=',$totalcommission)->where("find_in_set('-1',gettj) or find_in_set('".$member['levelid']."',gettj)")->select()->toArray();
			foreach($forcerebuyList as $forcerebuy){
				$orderwhere = [];
				$orderwhere[] = ['aid','=',$aid];
				$orderwhere[] = ['mid','=',$mid];
				$orderwhere[] = ['isfg','=',1];
				$orderwhere[] = ['status','in','1,2,3'];
				if($forcerebuy['fwtype'] == 1){
					$orderwhere[] = ['cid','in',$forcerebuy['categoryids']];
				}elseif($forcerebuy['fwtype'] == 2){
					$orderwhere[] = ['proid','in',$forcerebuy['productids']];
				}
				$totalprice = Db::name('shop_order_goods')->where($orderwhere)->sum('totalprice');
				if($totalprice < $forcerebuy['price']){
					if($forcerebuy['wfgtype'] == 0){
						Db::name('member')->where('id', $mid)->update(['commission_isfreeze' => 1]);
					}else{
						Db::name('member')->where('id', $member['id'])->update(['levelid' => $forcerebuy['wfglvid'], 'levelendtime' => 0]);
					}
				}
			}
		}
		
		/*佣金累计达到X元降级*/
		if(getcustom('member_level_down_commission')){
			$member = Db::name('member')->field('id,totalcommission,levelid,levelendtime,pid')->where('aid',$aid)->where('id',$mid)->find();
			$memberlevel =  Db::name('member_level')->field('id,down_level_totalcommission,down_level_id2,recovery_level_proid')->where('id',$member['levelid'])->find();
			if(!$member['isauto_down'] && $memberlevel['down_level_totalcommission']>0 && ($member['totalcommission']-$member['down_commission'])>=$memberlevel['down_level_totalcommission']){
				self::level_autodown_commission($aid,$member,$memberlevel['down_level_id2']);
			}
		}
        return ['status'=>1,'msg'=>''];
    }

    //加扶持基金
    public static function addFuchi($aid,$mid,$frommid,$commission,$remark){
        if(getcustom('commission_frozen')){
            if($commission==0) return ;
            $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
            if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

            $after = $member['fuchi_money'] + $commission;
            $update_member = ['fuchi_money'=>$after];
            Db::name('member')->where('aid',$aid)->where('id',$mid)->update($update_member);

            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $mid;
            $data['frommid'] = $frommid;
            $data['commission'] = $commission;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_fuchi_log')->insert($data);
            return ['status'=>1,'msg'=>''];
        }
    }
    //加冻结佣金
    public static function addXiaofei($aid,$mid,$frommid,$commission,$remark){
        if(getcustom('commission_xiaofei')){
            if($commission==0) return ;
            $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
            if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

            $after = $member['xiaofei_money'] + $commission;
            $update_member = ['xiaofei_money'=>$after];
            Db::name('member')->where('aid',$aid)->where('id',$mid)->update($update_member);

            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $mid;
            $data['frommid'] = $frommid;
            $data['commission'] = $commission;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_xiaofei_money_log')->insert($data);
            return ['status'=>1,'msg'=>''];
        }
    }

    //加通证
    public static function addtongzheng($aid,$mid,$money,$remark,$frommid=0,$paytype=''){
        if(getcustom('product_givetongzheng')) {
            if ($money == 0) return;
            $member = Db::name('member')->where('aid', $aid)->where('id', $mid)->lock(true)->find();
            if (!$member) return ['status' => 0, 'msg' => t('会员') . '不存在'];
            $after = $member['tongzheng'] + $money;
            Db::name('member')->where('aid', $aid)->where('id', $mid)->update(['tongzheng' => $after]);

            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $mid;
            $data['money'] = $money;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            $data['paytype'] = $paytype;
            $data['from_mid'] = $frommid;

            Db::name('member_tongzhenglog')->insert($data);

            $tmplcontent = [];
            $tmplcontent['first'] = '您的' . t('通证') . '发生变动，变动金额：' . $money;
            $tmplcontent['remark'] = '点击进入查看~';
            $tmplcontent['keyword1'] = date('Y-m-d H:i'); //变动时间
            $tmplcontent['keyword2'] = $remark;  //变动类型
            $tmplcontent['keyword3'] = (string)round($money, 2);  //变动金额
            $tmplcontent['keyword4'] = (string)round($after, 2);  //当前余额
            $tmplcontentNew = [];
            $tmplcontentNew['thing2'] = str_replace(',', '', mb_substr($remark, 0, 5));//消费项目
            $tmplcontentNew['amount3'] = round($money, 2);//消费金额
            $tmplcontentNew['amount4'] = round($after, 2);//卡内余额
            $tmplcontentNew['time6'] = date('Y-m-d H:i'); //变动时间
            $rs = \app\common\Wechat::sendtmpl($aid, $mid, 'tmpl_moneychange', $tmplcontent, m_url('pages/my/usercenter', $aid), $tmplcontentNew);
            //变动通知
            return ['status' => 1, 'msg' => ''];
        }
    }
    //获取余额
    public static function getmoney($member){
        if(!$member || !$member['id']) return '0.00';
        $member = db('member')->where(['id'=>$member['id']])->find();
        if(getcustom('w7moneyscore')) {
            static $w7moneyscore = -1;
            if($w7moneyscore == -1){
                $w7moneyscore = db('admin_set')->where(['aid'=>$member['aid']])->value('w7moneyscore');
            }
            $w7uniacid = db('admin_set')->where(['aid'=>$member['aid']])->value('w7uniacid');
//            Log::write([
//                'file' => __FILE__,
//                'line' => __LINE__,
//                '$w7uniacid' => $w7uniacid
//            ]);
            if($w7moneyscore == 1 && $w7uniacid){
                $fansinfo = Db::connect('w7')->table('ims_mc_mapping_fans')->where("uniacid='{$w7uniacid}' and (openid='{$member['mpopenid']}' or (unionid!='' && unionid is not null && unionid='{$member['unionid']}') or (openid!='' && openid is not null && openid='{$member['wxopenid']}'))")->find();
//                Log::write([
//                    'file' => __FILE__,
//                    'line' => __LINE__,
//                    '$fansinfo' => $fansinfo
//                ]);
                $uid = $fansinfo['uid'];
                $mcmember = Db::connect('w7')->table('ims_mc_members')->where(['uid'=>$uid])->find();
//                Log::write([
//                    'file' => __FILE__,
//                    'line' => __LINE__,
//                    '$uid' => $uid,
//                    '$mcmember' => $mcmember
//                ]);
                if(!$uid || !$mcmember) return '0.00';
                return $mcmember['credit2'];
            }
        }

        return $member['money'];
    }
    //获取积分
    public static function getscore($member){
        if(!$member || !$member['id']) return '0';
        $member = db('member')->where(['id'=>$member['id']])->find();

        if(getcustom('w7moneyscore')) {
            static $w7moneyscore = -1;
            if($w7moneyscore == -1){
                $w7moneyscore = db('admin_set')->where(['aid'=>$member['aid']])->value('w7moneyscore');
            }
            $w7uniacid = db('admin_set')->where(['aid'=>$member['aid']])->value('w7uniacid');
            if($w7moneyscore == 1 && $w7uniacid){
                $fansinfo = Db::connect('w7')->table('ims_mc_mapping_fans')->where("uniacid='{$w7uniacid}' and (openid='{$member['mpopenid']}' or (unionid!='' && unionid is not null && unionid='{$member['unionid']}') or (openid!='' && openid is not null && openid='{$member['wxopenid']}'))")->find();
                $uid = $fansinfo['uid'];
                $mcmember = Db::connect('w7')->table('ims_mc_members')->where(['uid'=>$uid])->find();
                if(!$uid || !$mcmember) return '0';
                return intval($mcmember['credit1']);
            }
        }

        return $member['score'];
    }

    public static function addw7moneyscore($aid,$member,$type,$money,$remark){
        $w7uniacid = db('admin_set')->where(['aid'=>$aid])->value('w7uniacid');
        if(empty($w7uniacid)) {
            return ['status'=>0,'msg'=>'w7uniacid empty'];
        }
        $fansinfo = Db::connect('w7')->table('ims_mc_mapping_fans')->where("uniacid='{$w7uniacid}' and (openid='{$member['mpopenid']}' or (unionid!='' && unionid is not null && unionid='{$member['unionid']}') or (openid!='' && openid is not null && openid='{$member['wxopenid']}'))")->find();
//        \think\facade\Log::write([
//            'file' => __FILE__,
//            'line' => __LINE__,
//            '$member' => $member,
//            '$fansinfo' => $fansinfo,
//            'sql' =>  Db::connect('w7')->table('ims_mc_mapping_fans')->getLastSql()
//        ]);
        $openid = $member['mpopenid'];
        if(!$openid) $openid = $member['unionid'];
        if(!$openid) $openid = $member['wxopenid'];
        if(!$fansinfo){
            $rec = array();
            $rec['acid'] = $w7uniacid;
            $rec['uniacid'] = $w7uniacid;
            $rec['openid'] = '';//$openid
            $rec['nickname'] = $member['nickname'];
            $rec['unionid'] = $member['unionid'];
            $rec['follow'] = $member['subscribe'] ? 1 : 0;
            $rec['followtime'] = $member['subscribe_time'] ? $member['subscribe_time'] : $member['createtime'];
            $rec['tag'] = base64_encode(serialize([
                'openid'=>$openid,
                'nickname'=>$member['nickname'],
                'sex'=>$member['sex'],
                'province'=>$member['province'],
                'city'=>$member['city'],
                'country'=>$member['country'],
                'unionid'=>$member['unionid'],
                'subscribe'=>$member['subscribe'],
                'subscribe_time'=>$member['subscribe_time'],
            ]));
            $member2 = array();
            $member2['uniacid'] = $w7uniacid;
            $member2['email'] = md5($openid).'@we7.cc';
            $member2['salt'] = random(8);
            $default_groupid = Db::connect('w7')->table('ims_mc_groups')->where(['uniacid'=>$w7uniacid,'isdefault'=>1])->value('groupid');
            $member2['groupid'] = $default_groupid;
            $member2['createtime'] = time();
            $member2['nickname'] = $member['nickname'];
            $member2['avatar'] = $member['headimg'];
            $member2['nationality'] = $member['country'];
            $member2['resideprovince'] = $member['province'];
            $member2['residecity'] = $member['city'];
            $config = include(ROOT_PATH.'config.php');
            $member2['password'] = md5($openid . $member2['salt'] . $config['authkey']);
            $rec['uid'] = Db::connect('w7')->table('ims_mc_members')->insertGetId($member2);
            Db::connect('w7')->table('ims_mc_mapping_fans')->insertGetId($rec);
        }
        $fansinfo = Db::connect('w7')->table('ims_mc_mapping_fans')->where("uniacid='{$w7uniacid}' and (openid='{$member['mpopenid']}' or (unionid!='' && unionid is not null && unionid='{$member['unionid']}') or (openid!='' && openid is not null && openid='{$member['wxopenid']}'))")->find();
        $uid = $fansinfo['uid'];
        $mcmember = Db::connect('w7')->table('ims_mc_members')->where(['uid'=>$uid])->find();
        if($uid == 0 || !$mcmember){
            $member2 = array();
            $member2['uniacid'] = $w7uniacid;
            $member2['email'] = md5($openid).'@we7.cc';
            $member2['salt'] = random(8);
            $default_groupid = Db::connect('w7')->table('ims_mc_groups')->where(['uniacid'=>$w7uniacid,'isdefault'=>1])->value('groupid');
            $member2['groupid'] = $default_groupid;
            $member2['createtime'] = time();
            $member2['nickname'] = $member['nickname'];
            $member2['avatar'] = $member['headimg'];
            $member2['nationality'] = $member['country'];
            $member2['resideprovince'] = $member['province'];
            $member2['residecity'] = $member['city'];
            $config = include(ROOT_PATH.'config.php');
            $member2['password'] = md5($openid . $member2['salt'] . $config['authkey']);
            $uid = Db::connect('w7')->table('ims_mc_members')->insertGetId($member2);
            Db::connect('w7')->table('ims_mc_mapping_fans')->where(['fanid'=>$fansinfo['fanid']])->update(['uid'=>$uid]);
            $mcmember = Db::connect('w7')->table('ims_mc_members')->where(['uid'=>$uid])->find();
        }
        $after = $mcmember['credit'.$type] + $money;
        Db::connect('w7')->table('ims_mc_members')->where(['uid'=>$uid])->update(['credit'.$type=>$after]);
        $data = array(
            'uid' => $uid,
            'credittype' => 'credit'.$type,
            'uniacid' => $w7uniacid,
            'num' => $money,
            'createtime' => time(),
            'operator' => '',
            'module' => 'ddwx_shop',
            'clerk_id' => '',
            'store_id' => '',
            'clerk_type' => 1,
            'remark' => $remark,
            'real_uniacid' => $uid
        );
        Db::connect('w7')->table('ims_mc_credits_record')->insert($data);

        if($type == 2){
            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $member['id'];
            $data['money'] = $money;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_moneylog')->insert($data);
            Db::name('member')->where(['aid'=>$aid,'id'=>$member['id']])->update(['money'=>$after]);
            Wechat::updatemembercard($aid,$member['id']);
        }else{
            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $member['id'];
            $data['score'] = $money;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_scorelog')->insert($data);
            Db::name('member')->where(['aid'=>$aid,'id'=>$member['id']])->update(['score'=>$after]);
            Wechat::updatemembercard($aid,$member['id'],$remark);
        }

        return ['status'=>1,'msg'=>''];
    }
	//获取多少级以内的下级
    /**
     * @param $aid
     * @param $mid
     * @param $levelnum 层级
     * @param $levelid 指定等级id 可以逗号多个等级id
     * @param $with_origin 脱离后作为原上级的升级条件，0不包含 1包含
     * @param $with_new 脱离后作为新上级的升级条件，0不包含 1包含
     * @return array
     */
	public static function getdownmids($aid,$mid,$levelnum=0,$levelid=0,$with_origin = 0,$with_new = 1){
		$downmids = [];
		if($levelid == 0){
            if($with_new)
			    $memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('find_in_set('.$mid.',path)')->select()->toArray();
            else
                $memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('find_in_set('.$mid.',path)')->where(function ($query){
                    $query->whereNull('pid_origin')->whereOr('pid_origin','=',0);
                })->select()->toArray();
            //230909兼容原有回归会员 pid_origin=0的情况
            if($with_origin){
                $memberlistOrigin = Db::name('member')->field('id,path')->where('aid',$aid)->where('pid_origin',$mid)->select()->toArray();
            }
		}else{
			$levelid = str_replace('，',',',$levelid);
            if($with_new)
			    $memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('levelid','in',$levelid)->where('find_in_set('.$mid.',path)')->select()->toArray();
            else
                $memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('levelid','in',$levelid)->where('find_in_set('.$mid.',path)')->where(function ($query){
                    $query->whereNull('pid_origin')->whereOr('pid_origin','=',0);
                })->select()->toArray();
			if (getcustom('plug_sanyang')) {
                $levelmids = Db::name('member_level_record')->where('aid', $aid)->where('levelid','in',$levelid)->column('mid');
                if(!empty($levelmids)) {
                    $levelmids = array_unique($levelmids);
                    $memberlist2 = Db::name('member')->field('id,path')->where('aid',$aid)->whereIn('id',$levelmids)->where('find_in_set('.$mid.',path)')->select()->toArray();
                    if(!empty($memberlist2)) {
                        $memberlist = array_merge($memberlist, $memberlist2);
                        $memberlist = array_unique($memberlist,SORT_REGULAR);
                    }
                }
            }
            if($with_origin){
                $memberlistOrigin = Db::name('member')->field('id,path')->where('aid',$aid)->where('levelid','in',$levelid)->where('pid_origin',$mid)->select()->toArray();
            }
		}
		foreach($memberlist as $member){
			if($levelnum == 0){
				$downmids[] = $member['id'];
			}else{
				$path = explode(',',$member['path']);
                $path = array_reverse($path);
				$key = array_search($mid,$path);
				if($key!==false && $key < $levelnum){
					$downmids[] = $member['id'];
				}
			}
		}
        if($with_origin && $memberlistOrigin){
            foreach($memberlistOrigin as $member){
                $downmids[] = $member['id'];
            }
        }
		return $downmids;
	}

    //获取多少级以外的下级
    /**
     * @param $aid
     * @param $mid
     * @param $levelnum 层级
     * @param $levelid 指定等级id
     * @param $with_origin 脱离后作为原上级的升级条件，0不包含 1包含
     * @param $with_new 脱离后作为新上级的升级条件，0不包含 1包含
     * @param string $where 其他查询条件
     * @return array
     */
    public static function getdowntotalmids($aid,$mid,$levelnum=0,$levelid=0,$with_origin = 0,$with_new = 1,$where='1=1'){
        $downmids = [];
        if($levelid == 0){
            if($with_new){
                $memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('find_in_set('.$mid.',path)')->where($where)->select()->toArray();
            } else{
                $memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('find_in_set('.$mid.',path)')->where(function ($query){
                    $query->whereNull('pid_origin')->whereOr('pid_origin','=',0);
                })->where($where)->select()->toArray();
            }
            if($with_origin){
                $memberlistOrigin = Db::name('member')->field('id,path')->where('aid',$aid)->where('pid_origin',$mid)->where($where)->select()->toArray();
            }
        }else{
            $levelid = str_replace('，',',',$levelid);
            if($with_new)
                $memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('levelid','in',$levelid)->where('find_in_set('.$mid.',path)')->where($where)->select()->toArray();
            else
                $memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('levelid','in',$levelid)->where('find_in_set('.$mid.',path)')->where($where)->where(function ($query){
                    $query->whereNull('pid_origin')->whereOr('pid_origin','=',0);
                })->select()->toArray();
            if (getcustom('plug_sanyang')) {
                $levelmids = Db::name('member_level_record')->where('aid', $aid)->where('levelid','in',$levelid)->column('mid');
                if(!empty($levelmids)) {
                    $levelmids = array_unique($levelmids);
                    $memberlist2 = Db::name('member')->field('id,path')->where('aid',$aid)->whereIn('id',$levelmids)->where('find_in_set('.$mid.',path)')->select()->toArray();
                    if(!empty($memberlist2)) {
                        $memberlist = array_merge($memberlist, $memberlist2);
                        $memberlist = array_unique($memberlist,SORT_REGULAR);
                    }
                }
            }
            if($with_origin){
                $memberlistOrigin = Db::name('member')->field('id,path')->where('aid',$aid)->where('levelid','in',$levelid)->where('pid_origin',$mid)->where($where)->select()->toArray();
            }
        }
        foreach($memberlist as $member){
            if($levelnum == 0){
                $downmids[] = $member['id'];
            }else{
                $path = explode(',',$member['path']);
                $path = array_reverse($path);
                $key = array_search($mid,$path);
                if($key!==false && $key >= $levelnum){
                    $downmids[] = $member['id'];
                }
            }
        }
        if($with_origin && $memberlistOrigin){
            foreach($memberlistOrigin as $member){
                $downmids[] = $member['id'];
            }
        }
        return $downmids;
    }

	//获取多少级以内的下级 小区的(即除了人数最多的区的所有区)
	public static function getdownmids_xiao($aid,$mid,$levelnum=0,$levelid=0){
		$childList = Db::name('member')->field('id,path')->where('aid',$aid)->where('pid',$mid)->select()->toArray();

		$downmidsArr = [];
		foreach($childList as $cmember){
			$thisdownmids = self::getdownmids($aid,$cmember['id'],$levelnum,$levelid);
			if(!$thisdownmids){
				$thisdownmids = $cmember['id'];
			}else{
				$thisdownmids[] = $cmember['id'];
			}
			$downmidsArr[] = ['count'=>count($thisdownmids),'mids'=>$thisdownmids];
		}
		$counts = array_column($downmidsArr,'count');
		array_multisort($counts,SORT_DESC,$downmidsArr);

		$downmids = [];
		foreach($downmidsArr as $k=>$v){
			if($k > 0){
				$downmids = array_merge($downmids,$v['mids']);
			}
		}
		return $downmids;
	}

    //获取多少级以内的下级 去除业绩最高的一个
	public static function getdownmids_removemax($aid,$mid,$levelnum=0,$levelid=0){
		$childList = Db::name('member')->field('id,path')->where('aid',$aid)->where('pid',$mid)->select()->toArray();
		$downmidsArr = [];
		foreach($childList as $cmember){
			$thisdownmids = self::getdownmids($aid,$cmember['id'],$levelnum,$levelid);
			if(!$thisdownmids){
				$thisdownmids = [$cmember['id']];
			}else{
				$thisdownmids[] = $cmember['id'];
			}
			//\think\facade\Log::write($thisdownmids);
			$fxordermoney = 0 + Db::name('shop_order_goods')->where('status','in','1,2,3')->where('mid','in',$thisdownmids)->sum('totalprice');
			$downmidsArr[] = ['count'=>count($thisdownmids),'mids'=>$thisdownmids,'fxordermoney'=>$fxordermoney];
		}
		//\think\facade\Log::write($downmidsArr);
		$counts = array_column($downmidsArr,'fxordermoney');
		array_multisort($counts,SORT_DESC,$downmidsArr);
		//\think\facade\Log::write($downmidsArr);

		$downmids = [];
		foreach($downmidsArr as $k=>$v){
			if($k > 0){
				$downmids = array_merge($downmids,$v['mids']);
			}
		}
		return $downmids;
	}
	//获取团队的会员id集合 团队中有和他平级或超过他等级的就跳出
	private static $mids = [];
	public static function getteammids($aid,$mid,$deep=999,$levelids=[],$mids=[],$thisdeep=0){
		if($thisdeep == 0){
			self::$mids = [];
		}
		$thisdeep = $thisdeep+1;
		if($thisdeep > $deep) return self::$mids;
        $where = [];
        $where[] = ['aid','=',$aid];
        $where[] = ['pid','=',$mid];
        if(!empty($levelids)){
            $where[] = ['levelid','in',$levelids];
        }
		$dowmids = Db::name('member')->where($where)->column('id');
		if($dowmids){
			foreach($dowmids as $downmid){
				if(!in_array($downmid,self::$mids)){
					self::$mids[] = $downmid;
					$down2mids = self::getteammids($aid,$downmid,$deep,$levelids,$mids,$thisdeep);
				}
			}
		}
		return self::$mids;
	}

    /**
     * @param $aid
     * @param $path
     * @param $where
     * @param $sort true 由近到远；false 由远到近
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getParentsByPath($aid,$path,$where=[],$sort=true)
    {
        if(empty($path)) return [];
        $parentList = Db::name('member')->where('aid',$aid)->where('id','in',$path)->where($where)
            ->order(Db::raw('field(id,'.$path.')'))->select()->toArray();
        if($parentList){
            if($sort) $parentList = array_reverse($parentList);
            return $parentList;
        }
        return [];
    }

    public static function addHongbaoEverydayEdu($aid,$mid,$money,$remark,$ogid=0){
        if($money==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        $after = $member['hongbao_everyday_edu'] + $money;
        Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['hongbao_everyday_edu'=>$after]);

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['money'] = $money;
        $data['ogid'] = $ogid;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        Db::name('member_hbe_edu_record')->insert($data);
        return ['status'=>1,'msg'=>''];
    }

    public static function addHongbaoLog($aid,$mid,$money,$remark){

        if($money==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        $afterTotal = $member['hongbao_ereryday_total'] + $money;

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['money'] = $money;
        $data['after'] = $afterTotal;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        Db::name('member_hbe_log')->insert($data);
        return ['status'=>1,'msg'=>''];
    }

    //加余额宝
    public static function addyuebaomoney($aid,$mid,$money,$remark,$type=0){

        if($money==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        $after = $member['yuebao_money'] + $money;
        Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['yuebao_money'=>$after]);

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['money'] = $money;
        $data['after'] = $after;
        $data['type']  = $type;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        Db::name('member_yuebao_moneylog')->insert($data);

        return ['status'=>1,'msg'=>''];
    }
    //加元宝
    public static function addyuanbao($aid,$mid,$yuanbao,$remark){
        if(getcustom('pay_yuanbao')){
            if($yuanbao==0) return ;
            $yuanbao = round($yuanbao,2);
            $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
            if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

            if($yuanbao < 0 && $member['yuanbao'] < $yuanbao*-1) return ['status'=>0,'msg'=>t('元宝').'不足'];

            $after = $member['yuanbao'] + $yuanbao;
            Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['yuanbao'=>$after]);

            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $mid;
            $data['yuanbao'] = $yuanbao;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            $data['type'] = 1;
            Db::name('member_yuanbaolog')->insert($data);
            return ['status'=>1,'msg'=>''];
        }
    }
    //加其他余额
    public static function addOtherMoney($aid,$mid,$type,$money,$remark){
        if(getcustom('other_money')){
            if($money==0) return ;
            $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
            if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

            if($type == 'money2'){
                $type_name = t('余额2');
                $log_type  = 2;
                if($money < 0 && $member['money2'] < $money*-1){
                    return ['status'=>0,'msg'=>$type_name.'不足'];
                }
                $after = $member['money2'] + $money;
                $up = Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['money2'=>$after]);
            }else if($type == 'money3'){
                $type_name = t('余额3');
                $log_type  = 3;
                if($money < 0 && $member['money3'] < $money*-1){
                    return ['status'=>0,'msg'=>$type_name.'不足'];
                }
                $after = $member['money3'] + $money;
                $up = Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['money3'=>$after]);
            }else if($type == 'money4'){
                $type_name = t('余额4');
                $log_type  = 4;
                if($money < 0 && $member['money4'] < $money*-1){
                    return ['status'=>0,'msg'=>$type_name.'不足'];
                }
                $after = $member['money4'] + $money;
                $up = Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['money4'=>$after]);
            }else if($type == 'money5'){
                $type_name = t('余额5');
                $log_type  = 5;
                if($money < 0 && $member['money5'] < $money*-1){
                    return ['status'=>0,'msg'=>$type_name.'不足'];
                }
                $after = $member['money5'] + $money;
                $up = Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['money5'=>$after]);
            }else if($type == 'frozen_money'){
                $type_name = t('冻结金额');
                $log_type  = 0;
                if($money < 0 && $member['frozen_money'] < $money*-1){
                    return ['status'=>0,'msg'=>$type_name.'不足'];
                }
                $after = $member['frozen_money'] + $money;
                $up = Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['frozen_money'=>$after]);
            }else{
                return ['status'=>0,'msg'=>'操作类型错误'];
            }

            if(!$up){
                return ['status'=>0,'msg'=>'操作失败'];
            }

            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $mid;
            $data['type']= $log_type;
            $data['money'] = $money;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_othermoneylog')->insert($data);

            $tmplcontent = [];
            $tmplcontent['first'] = '您的'.$type_name.'发生变动，变动金额：'.$money;
            $tmplcontent['remark'] = '点击进入查看~';
            $tmplcontent['keyword1'] = date('Y-m-d H:i'); //变动时间
            $tmplcontent['keyword2'] = $remark;  //变动类型
            $tmplcontent['keyword3'] = (string) round($money,2);  //变动金额
            $tmplcontent['keyword4'] = (string) round($after,2);  //当前余额
            $tmplcontentNew = [];
            $tmplcontentNew['thing2'] = $remark;//消费项目
            $tmplcontentNew['amount3'] = round($money,2);//消费金额
            $tmplcontentNew['amount4'] = round($after,2);//卡内余额
            $tmplcontentNew['time6'] = date('Y-m-d H:i'); //变动时间
            $rs = \app\common\Wechat::sendtmpl($aid,$mid,'tmpl_moneychange',$tmplcontent,m_url('pages/my/usercenter', $aid),$tmplcontentNew);
            return ['status'=>1,'msg'=>''];
        }
    }


    /**
     * 验证支付密码
     * @param $member 会员信息
     * @param $paypwd 输入的支付密码
     */
    public static function checkPayPwd($member,$paypwd){
        //设置过MD5加密的
        if($member['paypwd_rand']){
            if($member['paypwd'] == md5($paypwd.$member['paypwd_rand'])){
                return true;
            }else{
                return false;
            }
        }else{
            //未设置过MD5加密的
            if($member['paypwd'] == $paypwd){
                //验证通过后更新密码为加密后的
                $rand_str = make_rand_code(2,4);
                $paypwd = md5($paypwd.$rand_str);
                Db::name('member')->where('id',$member['id'])->update(['paypwd_rand'=>$rand_str,'paypwd'=>$paypwd]);
                return true;
            }else{
                return false;
            }
        }
    }
    //判断会员购车资金拿奖条件
    public static function goucheAble($mid){
        if(getcustom('teamfenhong_gouche')){
            $level_lists = Db::name('member_level')->column('gouche_down_num,gouche_levelid,gouche_bonus_total,sort','id');
            //判断会员是否满足拿奖条件
            $member_info = Db::name('member')->where('id',$mid)->field('id,levelid,gouche_able')->find();
            if(!$member_info['gouche_able']){
                //查询级别设置的拿奖条件
                $level_info = $level_lists[$member_info['levelid']];
                $level_limit = $level_lists[$level_info['gouche_levelid']]['sort'];//拿奖需要达到的级别
                //查询会员直推的前两个人
                $down_members = Db::name('member')->where('pid',$mid)
                    ->field('id,levelid')
                    ->order('createtime asc')
                    ->limit($level_info['gouche_down_num'])
                    ->select()->toArray();
                if(count($down_members)<$level_info['gouche_down_num']){
                    //dump($mid.'未达到购车基金资格1');
                    writeLog('会员'.$mid.'购车基金：直推下一级'.json_encode($down_members).'数量'.count($down_members).'<'.$level_info['gouche_down_num'].'未满足条件','gouche_bonus.log');
                    return false;
                }
                $gouche_able = 1;
                foreach($down_members as $k=>$down){
                    //判断级别是否达到条件
                    $level_sort = $level_lists[$down['levelid']]['sort'];
                    if($level_sort<$level_limit){
                        $gouche_able = 0;
                        writeLog('会员'.$mid.'购车基金：直推下一级会员'.$down['id'].'级别未达到'.$level_info['gouche_levelid'].'未满足条件','gouche_bonus.log');
                        break;
                    }
                    //判断累计收入是否达到条件
                    $down_commission = Db::name('member_commissionlog')->where('mid',$down['id'])->sum('commission');
                    $down_members[$k]['total_commission'] = $down_commission;
                    if(bccomp($down_commission,$level_info['gouche_bonus_total'],2)<0){
                        $gouche_able = 0;
                        writeLog('会员'.$mid.'购车基金：直推下一级会员'.$down['id'].'收入'.$down_commission.'<'.$level_info['gouche_bonus_total'].'未满足条件','gouche_bonus.log');
                        break;
                    }

                }
                //以上条件都能满足，更新会员购车基金资格
                if($gouche_able){
                    writeLog('会员'.$mid.'购车基金：直推下一级会员'.json_encode($down_members).'满足条件','gouche_bonus.log');
                    Db::name('member')->where('id',$mid)->update(['gouche_able'=>1]);
                    return true;
                }else{
                    writeLog('会员'.$mid.'购车基金：直推下一级会员'.json_encode($down_members).'未满足条件','gouche_bonus.log');
                    //dump($mid.'未达到购车基金资格2');
                    return false;
                }
            }
            writeLog('会员'.$mid.'购车基金：满足条件','gouche_bonus.log');
            return true;
        }
    }
    //判断会员旅游基金资格
    public static function lvyouAble($mid){
        if(getcustom('teamfenhong_lvyou')){
            $level_lists = Db::name('member_level')->column('lvyou_down_num,lvyou_levelid,lvyou_bonus_total,sort','id');
            $member_info = Db::name('member')->where('id',$mid)->field('id,levelid,lvyou_able')->find();
            if(!$member_info['lvyou_able']){
                //查询级别设置的拿奖条件
                $level_info = $level_lists[$member_info['levelid']];
                $level_limit = $level_lists[$level_info['lvyou_levelid']]['sort'];//拿奖需要达到的级别
                //查询会员直推的前两个人
                $down_members = Db::name('member')->where('pid',$mid)
                    ->field('id,levelid')
                    ->order('createtime asc')
                    ->limit($level_info['lvyou_down_num'])
                    ->select()->toArray();

                //查询下二级直推的前四个人
                $down_down_members = [];
                foreach($down_members as $down){
                    //查询下一级会员直推的前两个人
                    $down2_members = Db::name('member')->where('pid',$down['id'])
                        ->field('id,levelid')
                        ->order('createtime asc')
                        ->limit(2)
                        ->select()->toArray();
                    foreach($down2_members as $down2){
                        $down_down_members[] = $down2;
                    }
                    if(count($down_down_members)>=$level_info['lvyou_down_num']){
                        break;
                    }
                }
                if(count($down_down_members)<$level_info['lvyou_down_num']){
                    writeLog('会员'.$mid.'旅游基金：直推下二级'.json_encode($down_down_members).'数量'.count($down_down_members).'<'.$level_info['lvyou_down_num'].'未满足条件','lvyou_bonus.log');
                    return false;
                }
                $lvyou_able = 1;
                foreach($down_down_members as $k=>$down_down){
                    //判断级别是否达到条件
                    $level_sort = $level_lists[$down_down['levelid']]['sort'];
                    if($level_sort<$level_limit){
                        $lvyou_able = 0;
                        writeLog('会员'.$mid.'旅游基金：直推下二级会员'.$down_down['mid'].'级别'.$down_down['levelid'].'<'.$level_info['lvyou_levelid'].'未满足条件','lvyou_bonus.log');
                        break;
                    }
                    //判断累计收入是否达到条件
                    $down_commission = Db::name('member_commissionlog')->where('mid',$down_down['id'])->sum('commission');
                    $down_down_members[$k]['total_commission'] = $down_commission;
                    if(bccomp($down_commission,$level_info['lvyou_bonus_total'],2)<0){
                        $lvyou_able = 0;
                        writeLog('会员'.$mid.'旅游基金：直推下二级会员'.$down_down['mid'].'收入'.$down_commission.'<'.$level_info['lvyou_bonus_total'].'未满足条件','lvyou_bonus.log');
                        break;
                    }
                }
                //以上条件都能拿到，更新会员购车基金资格
                if($lvyou_able){
                    writeLog('会员'.$mid.'旅游基金：直推下二级会员'.json_encode($down_down_members).'满足条件','lvyou_bonus.log');
                    Db::name('member')->where('id',$mid)->update(['lvyou_able'=>1]);
                    return true;
                }else{
                    writeLog('会员'.$mid.'旅游基金：直推下二级会员'.json_encode($down_down_members).'未满足条件','lvyou_bonus.log');
                    return false;
                }
            }
            writeLog('会员'.$mid.'旅游基金：满足条件','lvyou_bonus.log');
            return true;
        }
    }

    public static function createMemberCode($aid,$mid)
    {
        if(getcustom('member_code')){
            $set = Db::name('member_code_set')->where('aid',$aid)->find();
            if($set['status'] == 1)
            {
                $last = Db::name('member')->where('aid',$aid)->where('member_code','<>','')->order('member_code','desc')->limit(1)->value('member_code');
                if($last){
                    $member_code = $last + 1;
                }else{
                    $member_code = $set['no_start'];
                }
                $member_code_img = createqrcode($member_code);
                Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['member_code'=>$member_code,'member_code_img'=>$member_code_img]);
                return ['status'=>1,'member_code'=>$member_code,'member_code_img'=>$member_code_img];
            }
            return ['status'=>0];
        }
    }

    /**
     * 自动降级
     */
    public function checkDownLevelCon($member,$level_data){
        if(getcustom('level_auto_down')){
            $is_down = 0;
            $date_start = $member['levelstarttime'];
            $date_end = $member['levelendtime'];
            //查询直推人数
            $is_down = 0;
            if($level_data['down_level_tjr']>0){
                $able_level_sort = Db::name('member_level')->where('id',$level_data['tjr_level_id'])->value('sort');
                $map = [];
                $map[] = ['sort','>=',$able_level_sort];
                $map[] = ['aid','=',$member['aid']];
                $able_level_ids = Db::name('member_level')->where($map)->column('id');
                $map = [];
                $map[] = ['pid','=',$member['id']];
                $map[] = ['createtime','between',[$date_start,$date_end]];
                $map[] = ['levelid','in',$able_level_ids];
                $tjnum = Db::name('member')->where($map)->count();

                if($tjnum<$level_data['down_level_tjr']){
                    $is_down = 1;
                    $desc = '直推人数'.$tjnum.',未达到'.$level_data['down_level_tjr'];
                }
            }
            //直推人数达到了，检测团队业绩
            if($is_down==0 && $level_data['down_level_teamyeji']>0){
                //团队业绩
                $yejiwhere = [];
                $yejiwhere[] = ['status','in','1,2,3'];
                $yejiwhere[] = ['createtime','between',[$date_start,$date_end]];
                $downmids = self::getteammids($member['aid'],$member['id']);
                $teamyeji = Db::name('shop_order_goods')->where('aid',aid)->where('mid','in',$downmids)->where($yejiwhere)->sum('real_totalprice');
                if($teamyeji<$level_data['down_level_teamyeji']){
                    $is_down = 1;
                    $desc = '团队业绩'.$teamyeji.',未达到'.$level_data['down_level_teamyeji'];
                }
            }
            if($level_data['down_level_tjr']<=0 && $level_data['down_level_teamyeji']<=0){
                //未设置检测条件，到期直接降级
                $is_down = 1;
                $desc = '级别到期';
            }
            return ['is_down'=>$is_down,'desc'=>$desc];

        }
    }

    //判断会员是否有团队收益的拿奖条件
    public static function teamshouyiAble($mid,$level_data){
        if(getcustom('teamfenhong_shouyi')){
            $order_money = Db::name('shop_order')
                ->where('mid','=',$mid)
                ->whereIn('status',[1,2,3])
                ->sum('totalprice');
            if($level_data['team_shouyi_ordermoney']>0 && $order_money<$level_data['team_shouyi_ordermoney']){
                writeLog('会员'.$mid.'团队收益：累计订单金额'.$order_money.'未达到'.$level_data['team_shouyi_ordermoney'],'teamfenhong_shouyi.log');
                return false;
            }
            writeLog('会员'.$mid.'团队收益：满足条件','teamfenhong_shouyi.log');
            return true;
        }
    }

    //透支额度钱包
    public static function addOverdraftMoney($aid,$mid,$money,$remark){
        if(getcustom('member_overdraft_money')) {
            if ($money == 0) return;
            $member = Db::name('member')->where('aid', $aid)->where('id', $mid)->lock(true)->find();
            if (!$member) return ['status' => 0, 'msg' => t('会员') . '不存在'];
            $after = $member['overdraft_money'] + $money;
            Db::name('member')->where('aid', $aid)->where('id', $mid)->update(['overdraft_money' => $after]);
            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $mid;
            $data['money'] = $money;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_overdraft_moneylog')->insert($data);
            self::uplv($aid, $mid);
            Wechat::updatemembercard($aid, $mid);

            $tmplcontent = [];
            $tmplcontent['first'] = '您的'.t('透支额度').'发生变动，变动金额：' . $money;
            $tmplcontent['remark'] = '点击进入查看~';
            $tmplcontent['keyword1'] = date('Y-m-d H:i'); //变动时间
            $tmplcontent['keyword2'] = $remark;  //变动类型
            $tmplcontent['keyword3'] = (string)round($money, 2);  //变动金额
            $tmplcontent['keyword4'] = (string)round($after, 2);  //当前余额
            $tmplcontentNew = [];
            $tmplcontentNew['thing2'] = $remark;//消费项目
            $tmplcontentNew['amount3'] = round($money, 2);//消费金额
            $tmplcontentNew['amount4'] = round($after, 2);//卡内余额
            $tmplcontentNew['time6'] = date('Y-m-d H:i'); //变动时间
            $rs = \app\common\Wechat::sendtmpl($aid, $mid, 'tmpl_moneychange', $tmplcontent, m_url('pages/my/usercenter', $aid), $tmplcontentNew);
            return ['status' => 1, 'msg' => ''];
        }
        return ['status' => 0, 'msg' => 'failed'];
    }
    
    //线下优惠券直接升级 $member=》 领取的会员
    public static function xianxiaUpLevel($member,$persendnum,$form_mid=0){
        if(getcustom('coupon_xianxia_buy')){
            //1.根据优惠券数量进行升级 2.发放奖励
            $aid = $member['aid'];
            $newlv = $now_level = Db::name('member_level')->where('aid',$aid)->where('id',$member['levelid'])->find();
            $lvlist = Db::name('member_level')->where('aid',$aid)->where('cid', 0)->where('sort','>',$now_level['sort'])->order('sort,id')->select()->toArray();
            $isup = false;
            foreach($lvlist as $lv){
                //如果下个等级的优惠券数量  =  当前转入的数量 就进行升级
                if($persendnum >=$lv['up_get_couponnum'] && $lv['up_get_couponnum']>0){
                    $newlv =  $lv;
                    $isup = true;
                }
            }
            if($isup){
                if ($newlv['yxqdate'] > 0) {
                    $levelendtime = strtotime(date('Y-m-d')) + 86400 + 86400 * $newlv['yxqdate'];
                } else {
                    $levelendtime = 0;
                }
                //判断是否是升级到最高等级 且判断是直接升级
                $next_level = Db::name('member_level')->where('aid',$aid)->where('sort','>',$newlv['sort'])->order('sort asc')->find();
                //升级记录 
                $level_record = Db::name('member_levelup_order')->where('aid',$aid)->where('mid',$member['id'])->find();
                $is_zt_up = 0;
                if(!$next_level && !$level_record){
                     $is_zt_up = 1;
                }
                $order = [
                    'aid' => $aid,
                    'mid' => $member['id'],
                    'from_mid' => $form_mid,
                    'pid' => $member['pid'],
                    'levelid' => $newlv['id'],
                    'title' => '续费延期',
                    'totalprice' => 0,
                    'createtime' => time(),
                    'levelup_time' => time(),
                    'beforelevelid' => $now_level['id'],
                    'form0' => '类型^_^购买优惠券升级',
                    'platform' => platform,
                    'status' => 2
                ];
                Db::name('member_levelup_order')->insert($order);
                Db::name('member')->where('id',$member['id'])->update(['levelid' => $newlv['id'],'levelendtime' => $levelendtime]);
                if($member['pid']){
                    \app\common\Member::uplv($aid,$member['pid']);
                }
                //直推发放奖励                   
                if($newlv['up_give_parent_money'] > 0 && $member['pid'] && ($is_zt_up==1 || $next_level)) {
                    \app\common\Member::addcommission($aid, $member['pid'], $member['id'], $newlv['up_give_parent_money'], '直推奖');
                }
            }
            //发放每组优惠券奖励 推荐人链中 父级的最近团购和分公司
            $parent = Db::name('member')->where('aid',$aid)->field('id,levelid,path')->where('id',$member['pid'])->find();
            //查询关系链
            $path  =$parent['path'].','.$parent['id'];
            $parent_list = Db::name('member')->where('aid',$aid)->where('id','in',$path)->field('id,levelid')->select()->toArray();
            $parent_list = array_reverse($parent_list);
           
            //发放排序
            $sort = Db::name('member_level')->where('aid',$aid)->where('sort','>',$newlv['sort'])->order('sort asc')->where('isdefault','=',0)->column('id');
            if($newlv['xianxia_coupon_vip_tj'] && $member['pid']){
                $xianxia_coupon_tj  = json_decode($newlv['xianxia_coupon_vip_tj'],true);
                $jl_data = $xianxia_coupon_tj[$parent['levelid']]; 
                if($jl_data){
                    //循环关系链的父级的等级 是否有和设置中levelid 相同，相同  取出 佣金
                    $have_level = [];//已送佣金的等级，直送最近的，防止重复
                    foreach($parent_list as $key=>$val){
                        $nowlevelid =  $val['levelid'];
                        if($jl_data[$nowlevelid] && !in_array($nowlevelid,$have_level)){
                            $have_level[] = $nowlevelid;
                            $money = $jl_data[$val['levelid']];
                            $commission_money =  dd_money_format($money*  $persendnum);
                            if($commission_money > 0) {
                                $p_levelname =Db::name('member_level')->where('id',$val['levelid'])->value('name');
                                $remark = '团队'.$p_levelname.'('.$val['id'].')推荐'.$newlv['name'].'('.$member['id'].')奖励';
                                $give_mid = self::getXianxiaSortMid($parent_list,$sort);
                                if($give_mid ==0){
                                    \app\common\Member::addcommission($aid, $val['id'], $member['id'], $commission_money, $remark);
                                }else{
                                    self::addXianxiaCommissionLog($aid, $val['id'], $give_mid, $member['id'],$commission_money,$persendnum, $remark);
                                }
                            }
                        }
                    }
                }
            }
           
            if($newlv['xianxia_full'] && $member['pid']){
                $xianxia_full = json_decode($newlv['xianxia_full'],true);
              
                if($xianxia_full['levelid'] ==$parent['levelid']){//推荐人的ID  = 设置的ID
                    $coupon_send = 0+Db::name('coupon_send')->where('aid',$aid)->where('from_mid',$parent['id'])->count();
                
                    if($xianxia_full['num'] && $coupon_send > $xianxia_full['num']){
                        $commission_money =  dd_money_format($xianxia_full['money']*  $persendnum);
                        if($commission_money > 0){
                            \app\common\Member::addcommission($aid, $parent['id'], $member['id'], $commission_money, '发券满'.$xianxia_full['num'].'组奖励');
                        }
                      
                    }
                } 
                
            }
        }
    }
    //线下优惠券 佣金应该谁发放
    public static function getXianxiaSortMid($parent_list,$sort){
        if(getcustom('coupon_xianxia_buy')) {
            $mid = 0;
            if($sort){
                foreach ($parent_list as $key=>$parent) {
                    if (in_array($parent['levelid'],$sort) && $key>0) {
                        $mid = $parent['id'];
                        break;
                    }
                }
            }
            return $mid;
        }
    }
    //添加线下优惠券 发放记录
    public static function addXianxiaCommissionLog($aid,$tomid,$give_mid,$frommid,$commission,$num,$remark=''){
        if(getcustom('coupon_xianxia_buy')) {
            $insert = [
                'aid' => $aid,
                'mid' => $give_mid,
                'tomid' => $tomid,
                'frommid' => $frommid,
                'commission' => $commission,
                'status' => 0,
                'remark' => $remark,
                'num' => $num,
                'createtime' => time()
            ];
            Db::name('xianxia_commission_log')->insert($insert);
        }
    }
    public static function xianxiaYeji($aid,$member,$yeji_reward_data,$month_start='',$month_end=''){
        //直推会员的支付金额
        $mids = Db::name('member')->where('aid',$aid)->where('pid',$member['id'])->column('id');
        $owhere = [];
        if($month_start && $month_end){
            $owhere[] = ['paytime','between',[$month_start,$month_end]];
        }
        $total_order_yeji =0+ Db::name('shop_order')->where('aid',$aid)->where('mid','in',$mids)->where('status','in',[1,2,3])->where($owhere)->sum('totalprice');
        //该用户转发的 =》 接收的用户的 等级 对应的商品的 会员价格，就是业绩
        $swhere = [];
        if($month_start && $month_end){
            $swhere[] = ['send_time','between',[$month_start,$month_end]];
        }
        $total_coupon_yeji = 0;   //(销售额)
        $my_total_coupon_yeji = 0;//按照自己的价格的销售额
        $sendcount = 0; //销售数量
        $shouyi = 0;    //收益额
        $coupon_send = Db::name('coupon_send')->where('aid',$aid)->where('from_mid',$member['id'])->where($swhere)->select()->toArray();
        foreach($coupon_send as $send){
            $total_coupon_yeji += $send['coupon_yeji'];
            $my_total_coupon_yeji += $send['from_coupon_yeji'];
            $shouyi +=$send['shouyi'];
            $sendcount++;
        }
        
        $total_yeji = dd_money_format($total_coupon_yeji + $total_order_yeji); //销售额 + 支付金额 = 总业绩
        $rewardkey = -1;
        foreach ($yeji_reward_data as $key => $reward){
            if($total_yeji >$reward['limit']){
                $rewardkey = $key;
            }
        }
        $get_commission = 0; //业绩奖励 
        if($yeji_reward_data[$rewardkey]){
            $get_commission = dd_money_format($yeji_reward_data[$rewardkey]['reward']/100 * $total_yeji);
        }
        
        
        //自己使用的也算
         $myuselist = Db::name('coupon_record')->alias('cr')
             ->join('coupon c','c.id = cr.couponid')
             ->where('cr.aid',$aid)->where('cr.mid',$member['id'])->where('cr.is_xianxia_buy',1)->where('status',1)->where('cr.from_mid','null')
             ->field('cr.*,c.productids')
             ->select()->toArray();
         $myuseryeji = 0;
        $myusecount = 0;
        foreach($myuselist as $record){
            $product_id =   explode(',',$record['productids']);
            $product = Db::name('shop_product')->where('aid',$aid)->where('id',$product_id[0])->find();
            if($product['lvprice']==1){
                $lvprice_data = json_decode($product['lvprice_data'],true);
                $myuseryeji += $lvprice_data[$member['levelid']];
            }else{
                $myuseryeji +=$product['sell_price'];
            }
            $myusecount++;
        }
        $total_coupon_yeji = $total_coupon_yeji + $myuseryeji;     
             
    
        //购买总数
        //目前我的优惠券数量
        $mycount =0+ Db::name('coupon_record')->where('aid',$aid)->where('mid',$member['id'])->where('is_xianxia_buy',1)->where('status',0)->count();
        
        //已发放下去的 （销售数）
        $mytoalcount =0+ Db::name('coupon_record')->where('aid',$aid)->where('mid',$member['id'])->where('is_xianxia_buy',1)->count();
        $total_count = $mytoalcount + $sendcount;
        $return =  [
            'totalyeji' => $total_yeji,//总业绩
            'order_yeji'  => $total_order_yeji,
            'coupon_yeji' => dd_money_format($total_coupon_yeji), //销售额，只出售优惠券额度
            'commission' => $get_commission,// 业绩奖励
            'shouyi' => $shouyi,          //收益额
            'mycount' => $mycount,        //目前剩余数量
            'sendcount' =>$sendcount + $myusecount,    //销售数
            'totalcount' => $total_count //总购买数
        ];
        return $return;
    }
	public function level_autodown_commission($aid,$member,$newlevelid){
		if(getcustom('member_level_down_commission')){
			$level_data = Db::name('member_level')->where('id',$newlevelid)->find();
			//var_dump($level_data);die;
			$data_u = [];
			$data_u['levelid'] = $newlevelid;
			if($level_data['yxqdate']>0){
				$data_u['levelendtime'] = $member['levelendtime']+86400 * $level_data['yxqdate'];
			}else{
				$data_u['levelendtime'] = 0;
			}
			$data_u['isauto_down']=1;
			$data_u['up_levelid']=$member['levelid'];
			$data_u['down_commission'] = $member['down_commission']+$member['totalcommission'];
			Db::name('member')->where('id', $member['id'])->update($data_u);
			
			//降级记录
			$order = [
				'aid' => $aid,
				'mid' => $member['id'],
				'from_mid' => $member['id'],
				'pid'=>$member['pid'],
				'levelid' => $newlevelid,
				'title' => '自动降级',
				'totalprice' => 0,
				'createtime' => time(),
				'levelup_time' => time(),
				'beforelevelid' => $member['levelid'],
				'form0' => '类型^_^' .'自动降级',
				'platform' => '',
				'status' => 2,
			];
			Db::name('member_levelup_order')->insert($order);
		}
	}
	public function recovery_level($aid,$member){
		if(getcustom('member_level_down_commission')){
			$level_data = Db::name('member_level')->where('id',$member['up_levelid'])->find();
			$data_u = [];
			$data_u['levelid'] = $member['up_levelid'];
			if($level_data['yxqdate']>0){
				$data_u['levelendtime'] = $member['levelendtime']+86400 * $level_data['yxqdate'];
			}else{
				$data_u['levelendtime'] = 0;
			}
			$data_u['isauto_down'] = 0;
			$data_u['up_levelid'] = 0;
			Db::name('member')->where('id', $member['id'])->update($data_u);
			//升级记录
			$order = [
				'aid' => $member['aid'],
				'mid' => $member['id'],
				'from_mid' => $member['id'],
				'pid'=>$member['pid'],
				'levelid' =>  $member['levelid'],
				'title' => '自动升级',
				'totalprice' => 0,
				'createtime' => time(),
				'levelup_time' => time(),
				'beforelevelid' => $level_data['id'],
				'form0' => '类型^_^' .'恢复等级',
				'platform' => '',
				'status' => 2,
			];
			Db::name('member_levelup_order')->insert($order);
		}
	}

	public function commission_to_score($sysset,$page=0,$limit=0,$last_mid=0){
        if(getcustom('commission_to_score')){
            $score_weishu = $sysset['score_weishu']??0;
            $butie_num = 0;//补贴金额
            if($sysset['commission_to_score_type']==0){
                //按利润百分比计算补贴金额
                $where = [];
                $where[] = ['aid','=',$sysset['aid']];
                $where[] = ['status','in','1,2,3'];
                $where[] = ['refund_num','=',0];
                $e_time = strtotime(date('Y-m-d 00:00:00'));
                $s_time = $e_time-86400;
                $where[] = ['paytime','between',[$s_time,$e_time]];
                $orders = Db::name('shop_order_goods')->where($where)->field('sum(real_totalprice- cost_price * num) cost_price_total')->find();

                $butie_num = bcmul($orders['cost_price_total'],$sysset['commission_to_score_money']/100,2);
            }else{
                //按固定金额计算补贴金额
                $butie_num = $sysset['commission_to_score_money'];
            }
            if($butie_num<=0){
                return ['status'=>0,'msg'=>'补贴金额为0'];
            }

            $where = [];
            $where[] = ['aid','=',$sysset['aid']];
            $where[] = ['score','>',0];
            $where[] = ['id','>',$last_mid];
            //计算全网总佣金
            $commission_total = Db::name('member')->where($where)->field('id,commission,score')->sum('score');
            $commission_total = dd_money_format($commission_total,$score_weishu);
            if($commission_total<0){
                if($butie_num<=0){
                    return ['status'=>0,'msg'=>'全网'.t('佣金',$sysset['aid']).'为0'];
                }
            }
            //查询会员，循环处理
            if($page>0 && $limit>0){
                $member_lists = Db::name('member')->where($where)->field('id,commission,score')->page(1,$limit)->order('id asc')->select()->toArray();
            }else{
                $member_lists = Db::name('member')->where($where)->field('id,commission,score')->order('id asc')->select()->toArray();
            }
            $sql = Db::getlastSql();
            writeLog('第'.$page.'页，'.$limit.',上一次最后一个会员ID'.$last_mid.',sql::'.$sql.'，共'.count($member_lists).'条','toscore.log');
            if(count($member_lists)<=0){
                return ['status'=>0,'msg'=>'全部处理完成！'];
            }
            $commission_to_score_bili = $sysset['commission_to_score_bili']>0?$sysset['commission_to_score_bili']:100;
            $sucnum = bcmul(($page-1),$limit);
            foreach($member_lists as $member){
                $num = bcmul(bcdiv($member['score'],$commission_total,4),$butie_num,$score_weishu);
                if($num<=0){
                    continue;
                }
                if($num>$member['score']){
                    $num = $member['score'];
                }
                $commission_num = bcmul($num,$commission_to_score_bili/100,2);
                if($num<=0 || $commission_num<=0){
                    continue;
                }
                //减少积分
                $res = self::addscore($sysset['aid'],$member['id'],-$num,'转入'.t('佣金',$sysset['aid']));
                //增加佣金
                $res = self::addcommission($sysset['aid'],$member['id'],0,$commission_num,t('积分',$sysset['aid']).'转入');
                //插入转换日志
                $log = [];
                $log['aid'] = $sysset['aid'];
                $log['mid'] = $member['id'];
                $log['commission_to_score_type'] = $sysset['commission_to_score_type'];
                $log['butie_num'] = $butie_num;
                $log['commission'] = $member['score'];
                $log['commission_total'] = $commission_total;
                $log['num'] = $num;
                $log['w_day'] = date('Ymd');
                $log['w_time'] = time();
                Db::name('commission_toscore_log')->insert($log);
                $sucnum ++;
                $last_mid = $member['id'];
            }
            if($sucnum<=0){
                return ['status'=>0,'msg'=>'全部处理完成！'];
            }
            return ['status'=>1,'msg'=>'操作成功！','sucnum'=>$sucnum,'last_mid'=>$last_mid];
        }
    }

    public static function addfhcopies($aid,$mid,$copies=0,$remark='',$frommid=0){
        if(getcustom('fenhong_jiaquan_bylevel')) {
            if ($copies == 0) return;
            $copies = intval($copies);
            $member = Db::name('member')->where('aid', $aid)->where('id', $mid)->lock(true)->find();
            if (!$member) return ['status' => 0, 'msg' => t('会员') . '不存在'];

            $after = $member['fhcopies'] + $copies;
            Db::name('member')->where('aid', $aid)->where('id', $mid)->update(['fhcopies' => $after]);
            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $mid;
            $data['copies'] = $copies;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_fhcopies_log')->insert($data);
            return ['status' => 1, 'msg' => ''];
        }
    }

    //查询团队订单和小区团队订单数量
    public static function getTeamOrderNum($aid,$mid,$levelnum=0,$levelid=0){
        if(getcustom('up_level_teamorder')){
            //统计团队订单数量
            $childrens = Db::name('member')->where('aid',$aid)->where('pid',$mid)->column('id');
            $order_arr = [];
            foreach($childrens as $chid_mid){
                $downmids = self::getdownmids($aid,$chid_mid,$levelnum-1,$levelid);
                if($downmids){
                    $downmids[] = $chid_mid;
                }else{
                    $downmids = [$chid_mid];
                }
                $map = [];
                $map[] = ['aid','=',$aid];
                $map[] = ['mid','in',$downmids];
                $map[] = ['status','in',[1,2,3]];
                $teamorder_count = Db::name('shop_order')->where($map)->count();
                $order_arr[] = $teamorder_count?:0;
            }
            $max = max($order_arr);
            $teamorder_count = array_sum($order_arr);
            $teamorder_small_count = bcsub($teamorder_count,$max);
            return [
                'teamorder_count' => $teamorder_count?:0,
                'teamorder_small_count' => $teamorder_small_count?:0
            ];
        }

    }

    //分销补贴按期发放
    public static function commission_butie($aid,$ids=[]){
        //查询所有待发放补贴
        $now_time = time();
        if($ids){
            $lists = Db::name('member_commission_butie')->where('aid',$aid)->where('status',0)->whereIn('id',$ids)->select()->toArray();
        }else{
            $lists = Db::name('member_commission_butie')->where('aid',$aid)->where('status',0)->where('next_send_time','<=',$now_time)->select()->toArray();
        }
        if(!$lists){
            return true;
        }
        foreach($lists as $v){
            $can_send = 0;
            if($v['send_circle']==0){
                $can_send = 1;
            }else if($now_time>$v['next_send_time']){
                $can_send = 1;
            }
            if(!$can_send){
                continue;
            }
            $send_bonus = bcdiv($v['commission'],$v['fx_butie_circle'],2);
            //发放补贴
            $send_circle = $v['send_circle'] + 1;
            if($send_circle>=$v['fx_butie_circle']){
                //最后一期发放剩余所有的
                $send_bonus = $v['remain'];
            }
            $remark = '订单'.$v['orderid'].'产生的'.t('分销补贴',$aid).'第'.$send_circle.'期发放';
            \app\common\Member::addcommission($aid,$v['mid'],$v['frommid'],$send_bonus,$remark,1,'commission_butie');
            //更新记录
            $data_u = [];
            $data_u['have_send'] = bcadd($v['have_send'],$send_bonus,2);
            $data_u['remain'] = bcsub($v['commission'],$data_u['have_send'],2);
            $data_u['send_circle'] = $send_circle;
            if($send_circle>=$v['fx_butie_circle'] || $data_u['remain']<=0){
                $data_u['status'] = 1;
            }
            //判断下一次发放时间
            if($v['fx_butie_type']==1){
                //按周
                $send_day = $v['fx_butie_send_week'];
                $s_time = strtotime('+1 week last monday');
                $send_time = $s_time+$send_day*86400-86400;
            }else{
                //按月
                $s_time = strtotime(date('Y-m-t 23:59:59'))+86400;
                $t = date('t',$s_time);
                $send_day = $v['fx_butie_send_day'];
                if($t<$send_day){
                    //有可能设置31号，但是本月只到30号，取本月最后一天
                    $send_day = $t;
                }
                $send_time = strtotime(date('Y-m-'.$send_day,$s_time));
            }
            $data_u['next_send_time'] = $send_time;
            Db::name('member_commission_butie')->where('id',$v['id'])->update($data_u);
            //插入发放明细
            $data_log = [];
            $data_log['aid'] = $aid;
            $data_log['mid'] = $v['mid'];
            $data_log['pid'] = $v['id'];
            $data_log['send_num'] = $send_bonus;
            $data_log['send_circle'] = $send_circle;
            $data_log['send_time'] = time();
            Db::name('member_commission_butie_log')->insert($data_log);
        }
        return true;
    }

    //上级佣金按级差发放
    public static function parent_commission($leveldata,$parent,$mid,$aid){
        if(getcustom('member_levelup_parentcommission_jicha')){
            $levelup_parentcommission = json_decode($leveldata['levelup_parentcommission'],true);
            if($parent['pid']){
                $pids = $parent['path'];
                $parentList = Db::name('member')->where('id','in',$pids)->order(Db::raw('field(id,'.$pids.')'))->select()->toArray();
                $parentList = array_reverse($parentList);
                $jicha = $levelup_parentcommission[$parent['levelid']];
                foreach($parentList as $parent2){
                    $commission = $levelup_parentcommission[$parent2['levelid']];
                    $real_commission = bcsub($commission,$jicha,2);
                    $real_commission = $real_commission>0?$real_commission:0;
                    if($real_commission<=0){
                        continue;
                    }
                    $jicha = $commission;
                    \app\common\Member::addcommission($aid, $parent2['id'],$mid, $real_commission, '团队会员升级奖励');
                }
            }
            return true;
        }

    }

    //释放通证
    public static function release_tongzheng($sysset){
        if(getcustom('product_givetongzheng')) {
            $aid = $sysset['aid'];
            $release_bili = $sysset['tongzheng_release_bili'];
            $lists = Db::name('tongzheng_order_log')->where('aid', $aid)->where('status', '=', 0)->select()->toArray();
            if(!$lists){
                return true;
            }
            foreach ($lists as $order) {
                $order_status = Db::name('shop_order')->where('id',$order['orderid'])->value('status');
                if(!$order_status || !in_array($order_status,[1,2,3])){
                    Db::name('tongzheng_order_log')->where('id',$order['id'])->update(['status'=>2]);
                    continue;
                }
                //计算释放数量
                $release_num = bcmul($order['tongzheng'], $release_bili / 100, 3);
                if ($release_num <= 0) {
                    continue;
                }
                $status = 0;
                if($release_num>$order['remain']){
                    $release_num = $order['remain'];
                    $status = 1;
                }
                $remark = date('Y-m-d H:i:s') . '订单id'.$order['orderid'].t('通证') . '释放';
                //增加通证
                \app\common\Member::addtongzheng($aid, $order['mid'], $release_num, $remark);
                //记录释放记录
                $log = [];
                $log['aid'] = $aid;
                $log['mid'] = $order['mid'];
                $log['pid'] = $order['id'];
                $log['tongzheng'] = $order['tongzheng'];
                $log['release_bili'] = $release_bili;
                $log['release_num'] = $release_num;
                $log['createtime'] = time();
                $log['remark'] = $remark;
                Db::name('tongzheng_release_log')->insert($log);
                //更新释放数量
                $data_u = [];
                $data_u['remain'] = bcsub($order['remain'],$release_num,3);
                $data_u['release_num'] = bcadd($order['release_num'],$release_num,3);
                $data_u['release_time'] = time();
                $data_u['status'] = $status;
                Db::name('tongzheng_order_log')->where('id',$order['id'])->update($data_u);
            }
            return true;
        }
    }
}